簡體   English   中英

Google maps API - 按地址javascript添加標記

[英]Google maps API - add marker by address javascript

我有地址數據庫,我想在谷歌地圖上添加標記。

它只顯示默認標記,看起來像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>

您未獲得預期結果的原因是因為您提供的示例中存在錯誤的代碼放置。 您正在嘗試在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>

現場演示這里

希望能幫助到你!

您的代碼中存在多個錯誤。 通常,它現在應該看起來不錯:

var geocoder;
var map;
var address = "new york city";

function initMap() {
    geocoder = new google.maps.Geocoder();

    var uluru = { lat: -25.363, lng: 131.044 };
    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) {
        console.log(results);
        var latLng = {lat: results[0].geometry.location.lat (), lng: results[0].geometry.location.lng ()};
        console.log (latLng);
        if (status == 'OK') {
            var marker = new google.maps.Marker({
                position: latLng,
                map: map
            });
            console.log (map);
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

這是您的錯誤列表:

  • 當Google Maps api完全加載時,您必須初始化地理編碼。 這意味着您必須使用以下代碼行: geocoder = new google.maps.Geocoder(); initMap ()
  • 初始化地圖時,您必須引用全局變量。 在您的代碼中,您將在函數中創建一個新的變量映射。 但是,你必須通過全局的變量映射。
  • 當你想獲得地理編碼器結果的位置時,你必須通過這行代碼: results[0].geometry.location.lat ()

您可以參考文檔

如果您有疑問,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM