在 javascript 中,navigator.geolocation.watchPosition() 方法用于注册一个处理函数,该处理函数将在每次设备位置发生变化时自动调用。您还可以选择指定错误处理回调函数。
语法:
navigator.geolocation.watchPosition(success[, error[, options]])
-
成功
一个将 Position 对象作为输入参数的回调函数。
-
错误(可选)
将 PositionError 对象作为输入参数的可选回调函数。
-
选项(可选)
一个可选的 PositionOptions 对象。
现在,对于您的问题,您可以使用此代码。小心,你应该用你的谷歌API密钥替换YOUR-API-KEY:
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
var marker = new google.maps.Marker({
position: pos,
map: map,
title: "Test"
});
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
getLocationUpdate ();
}
function showLocation(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
marker.setPosition(pos);
map.setCenter(pos);
alert("Latitude : " + pos.lat + " Longitude: " + pos.lng);
}
function errorHandler(err) {
if(err.code == 1) {
alert("Error: Access is denied!");
}
else if( err.code == 2) {
alert("Error: Position is unavailable!");
}
}
function getLocationUpdate(){
if(navigator.geolocation){
// timeout at 60000 milliseconds (60 seconds)
var options = {
enableHighAccuracy: false,
timeout: 5000,
maximumAge: 0
};
var geoLoc = navigator.geolocation;
geoLoc.watchPosition(showLocation, errorHandler, options);
}
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY&callback=initMap">
</script>