美文网首页
根据地名定位谷歌MAP

根据地名定位谷歌MAP

作者: MingSha | 来源:发表于2017-03-05 21:54 被阅读0次

    许多时候,我们必须通过经纬度来定位地图,有没有办法通过地面直接定位。
    其中的address = 'Paris, France';即位定位到巴黎。
    代码如下

    <div id="map-canvas"></div>
    <style type="text/css">#map-canvas {
        height: 400px;
    }</style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
    <script type="text/javascript">
        
        var geocoder;
    var map;
    
    function initialize() {
        
        geocoder = new google.maps.Geocoder();
        
        var latlng = new google.maps.LatLng(-34.397, 150.644);
        var mapOptions = {
            zoom: 8,
            center: latlng
        };
        
        map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
        
        // Call the codeAddress function (once) when the map is idle (ready)
        google.maps.event.addListenerOnce(map, 'idle', codeAddress);
    }
    
    function codeAddress() {
        
        // Define address to center map to
        var address = 'Paris, France';
        
        geocoder.geocode({
            'address': address
        }, function (results, status) {
            
            if (status == google.maps.GeocoderStatus.OK) {
                
                // Center map on location
                map.setCenter(results[0].geometry.location);
                
                // Add marker on location
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
                
            } else {
                
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
    }
    initialize();
    </script>
    

    相关文章

      网友评论

          本文标题:根据地名定位谷歌MAP

          本文链接:https://www.haomeiwen.com/subject/ronegttx.html