【问题标题】:How to use Address instead of Lat/Long in Google Map API如何在 Google Map API 中使用地址而不是纬度/经度
【发布时间】:2016-06-06 15:50:53
【问题描述】:

我想使用 Google 地图标记来标记我们提供服务的地点。 使用 Lat/Long 的我的代码运行良好,但在我的项目中,我需要使用城市名称而不是 lat/long。我怎么能做到这一点有什么办法做到这一点? 这是我的代码

        <div id="map" style="height:500px;"></div>
    <script>
        var neighborhoods = [
          { lat: 31.6400, lng: 74.8600 },
          { lat: 28.6139, lng: 77.2090 },
          { lat: 12.9667, lng: 77.5667 },
          { lat: 31.3260, lng: 75.5760 },
          { lat: 30.7500, lng: 76.7800 },
          { lat: 30.3400, lng: 76.3800 }
        ];

        var markers = [];
        var map;

        function initMap() {
            map = new google.maps.Map(document.getElementById('map'), {
                zoom: 5,
                center: { lat: 28.6139, lng: 77.2090 }
            });
        }

        function drop() {
            clearMarkers();
            for (var i = 0; i < neighborhoods.length; i++) {
                addMarkerWithTimeout(neighborhoods[i], i * 200);
            }
        }

        function addMarkerWithTimeout(position, timeout) {
            window.setTimeout(function () {
                markers.push(new google.maps.Marker({
                    position: position,
                    map: map,
                    title: 'Jassie',
                    animation: google.maps.Animation.DROP
                }));
            }, timeout);
        }

        function clearMarkers() {
            for (var i = 0; i < markers.length; i++) {
                markers[i].setMap(null);
            }
            markers = [];
        }
        $(window).load(function () {
            drop();
        });
    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=API_Key&signed_in=true&callback=initMap">  </script>
</div>

【问题讨论】:

标签: javascript html google-maps web


【解决方案1】:

根据规范 (https://developers.google.com/maps/documentation/javascript/markers),您必须使用 long/lat 值来添加标记。但是,您可以使用 Google Geocoding API (https://developers.google.com/maps/documentation/geocoding/intro) 将地址转换为 long/lat 值。所以基本上你的流程变成了:

  • 地理编码地址 x
  • 获取结果并将其用于标记中

【讨论】:

    【解决方案2】:

    您必须使用地理编码 API。将地址设为 Lat/lng 的示例:

     doGeocode: function (address, postal_code, callback) {
        console.log("TEST: "+address.toString());
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({
            'address': address,
            'componentRestrictions': {
                'postalCode': postal_code,
                'country': 'de'
            }
        }, function (results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                callback(results);
            } else {
                //Error handling
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    

    注意:地址也可以包含门牌号,但要输入空格。

    还有一种反向方法可以从 Lat/lng 获取地址。以防万一有人需要:

    reverseGeocoder: function (lat, lng, callback) {
    
        var geocoder = new google.maps.Geocoder;
        var addressComponents = {};
        geocoder.geocode({
            'location': {
                lat:lat,
                lng: lng
            }
        }, function (results, status){
            if(status === google.maps.GeocoderStatus.OK){
                if (results[1]) {
                    var result = results[0].address_components;
    
                    for (var i = 0; i < result.length; i++) {
                        if (result[i].types[0] == "route") {
                            console.log(result[i].long_name);
                            addressComponents.route = result[i].long_name
                        }
                        if (result[i].types[0] == "street_number") {
                            console.log(result[i].long_name);
                            addressComponents.street_number = result[i].long_name
                        }
                        if (result[i].types[0] == "locality") {
                            console.log(result[i].long_name);
                            addressComponents.locality = result[i].long_name
                        }
                        if (result[i].types[0] == "postal_code") {
                            console.log(result[i].long_name);
                            addressComponents.postal_code = result[i].long_name
                        }
                    }
                    callback(addressComponents);
                } else {
                    alert('No information found.');
                }
    
            }else {
                alert("Die geolocation abfrage konnte leider nicht ausgeführt werden. "+status);
            }
        });
    

    从上面的第一个函数中,您将获得 Lat/lng。 然后简单地使用这样的函数:

    var newMarkers = [];        //Global marker array
     marker: function (lat, lng) {
        console.log("new marker");
    
        //console.log("LAT: "+lat+ "LNG: "+lng);
        var marker = new google.maps.Marker({
            position: {lat: lat, lng: lng},
            icon: icon,
            map: map
        });
        markers.push(marker);
        marker.addListener('click', function () {
            //InfoWindow or whatever u want
        });
    
        map.setCenter({lat: lat, lng: lng});
        map.setZoom(16);
    },
    

    【讨论】:

      猜你喜欢
      • 2013-04-02
      • 1970-01-01
      • 2013-02-23
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      • 2014-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多