javascript - 如何移动谷歌地图标记并获取当前的纬度和经度

标签 javascript google-maps google-maps-api-3

我想使用谷歌地图来获取用户当前的纬度和经度:

    <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/

相关文章:

javascript - reactjs 复选框列表组件 - 更新父级中的状态更改

javascript - ionic 2 : Map markers not appearing

javascript - Google map 标记工具提示

javascript - 输入没有像它应该的那样滚动到最右边

java - Greasemonkey 脚本使用小程序标签更改 img 标签

javascript - 如何在 react 类之外访问纯 js 值

google-maps - 谷歌地图的人口普查覆盖?

javascript - 如何在网页中的谷歌地图上添加标记

javascript - 计算谷歌地图街景的滚动 Angular

javascript - 无法设置经度从 -180 到 0 的 LatLngBounds