这是需要在Angular2加载的Map Component之后调用的JS代码。代码在组件模板中定义。
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>
如何从getLocation()
方法中的组件调用onNgInit
函数? (或者如果可能的话,这可以以更好的方式设计吗?)
接受答案和其他SO答案的最终解决方案:
Working Code In Plunker - integrating Geolocation, angular2-google-maps and Angular2 (RC1)
答案 0 :(得分:1)
在脚本末尾添加
window.myGetLocation = getLocation;
在Angular组件中:
ngOnInit() {
console.log(window.myGetLocation());
}
如果你添加
declare var navigator;
到您的打字稿脚本文件,您可以在Angular2组件中使用navigator.geolocation...
。