Google Map Javascript Api 坐标/经纬度拾取

html,JavaScript 2017-12-03

主要参考的API在https://developers.google.com/maps/documentation/javascript/3.exp/reference?authuser=1#Map
中的Events.click

代码如下,注意需要修改KEY

<!DOCTYPE html>
<html>
<head>
    <style>
        #map {
            height: 600px;
            width: 100%;
        }
    </style>
</head>
<body>
<div id="map"></div>
<script>
    function initMap() {
        var uluru = {lat: 23.4302665, lng: 121.5833201};
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 7,
            center: uluru
        });
        var marker = new google.maps.Marker;

        map.addListener('click', function(ApiMouseEvent) {

            marker.setMap(null);

            var lat = ApiMouseEvent.latLng.lat();
            var lng = ApiMouseEvent.latLng.lng();
            var locationJson = ApiMouseEvent.latLng.toJSON()

            var contentString = '<div id="content" style="text-align:center;">'+lat+','+lng+'<br/><button onclick="select('+lat+','+lng+');">选择该位置</button></div>';

            var infowindow = new google.maps.InfoWindow({
                content: contentString
            });
            marker = new google.maps.Marker({
                position: locationJson,
                map: map,
                title: lat+','+lng
            });

            infowindow.open(map, marker);
        });


    }
</script>
<script async defer
        src="https://maps.googleapis.com/maps/api/js?key=YOURKEY&callback=initMap">
</script>
<script>
    function select(lat,lng){
        console.log(lat)
        console.log(lng)
    }
</script>
</body>
</html>

本文由 Jazzy 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论