Google maps API - 按地址javascript添加标记

Avi*_*yal 10 javascript google-maps geocoding google-maps-api-3

我有地址数据库,我想在谷歌地图上添加标记.

它只显示默认标记,看起来像geocoder.geocode()什么都不做.举个例子,我试图在"纽约市"上添加一个标记,但没有成功.

<script>
    var geocoder;
    var map;
    var address = "new york city";
    geocoder = new google.maps.Geocoder();
    function initMap() {
        var uluru = { lat: -25.363, lng: 131.044 };
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 4,
            center: uluru
        });
        var marker = new google.maps.Marker({
            position: uluru,
            map: map
        });
        codeAddress(address);

    }

    function codeAddress(address) {

        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == 'OK') {
                    var marker = new google.maps.Marker({
                    position: address,
                    map: map
                });
            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    }


</script>
<script src="https://maps.googleapis.com/maps/api/js?key=XXX&callback=initMap"
    async defer></script>
Run Code Online (Sandbox Code Playgroud)

小智 20

您未获得预期结果的原因是因为您提供的示例中存在错误的代码放置.您正在尝试在Google地图完全加载之前获取Google Maps API地理编码器的新实例.因此,由于此未捕获的ReferenceError,Google Maps API地理编码器将无法正常工作:未定义Google.您应该在initMap()函数中获得一个新的Google Maps API Geocoder实例.

您可以查看Maps JavaScript API地理编码 以了解详情.

您还可以查看地理编码地址时的最佳做法.

另请注意,发布Google Maps APi相关问题时,不应包含API_KEY.

这是整个代码:

<!DOCTYPE html>
<html>
  <head>
    <title>Geocoding service</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      var geocoder;
      var map;
      var address = "new york city";
      function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 8,
          center: {lat: -34.397, lng: 150.644}
        });
        geocoder = new google.maps.Geocoder();
        codeAddress(geocoder, map);
      }

      function codeAddress(geocoder, map) {
        geocoder.geocode({'address': address}, function(results, status) {
          if (status === 'OK') {
            map.setCenter(results[0].geometry.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);
          }
        });
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

现场演示这里.

希望能帮助到你!