我想使用谷歌地图来获取用户当前的纬度和经度:
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCfbbmUkl56UuSeZ5nSOwsKTNxplmnheuU&callback=initialize&language=en" async defer></script>
用户应该更改标记,我会得到新的纬度和经度。
可以这样做吗?
最佳答案
使用 HTML 地理定位方法自动检测用户位置的代码片段。确保您的浏览器在运行此应用程序时启用位置,并提供正确的谷歌地图 API 链接和最无效的 API key 。这是 MDN Using geolocation 的链接您可以在其中找到有关地理位置和浏览器支持信息的详细信息。
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Click Me to show Your Location.</button>
<div id="map" style="width:100%;height:500px"></div>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var myCenter = new google.maps.LatLng(lat, lng);
var mapCanvas = document.getElementById("map");
var mapOptions = {
center: myCenter,
zoom: 5
};
var map = new google.maps.Map(mapCanvas, mapOptions);
var marker = new google.maps.Marker({
position: myCenter
});
marker.setMap(map);
// Zoom to 9 when clicking on marker
google.maps.event.addListener(marker, 'click', function () {
map.setZoom(9);
map.setCenter(marker.getPosition());
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=myMap"></script>
</body>
</html>
希望这对您有帮助
关于javascript - 如何移动谷歌地图标记并获取当前的纬度和经度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43962725/