簡體   English   中英

未定義Google Maps Geocoder

[英]Google maps geocoder not defined

我正在編寫AngularJs 1.x應用程序(太懶了,無法學習TypeScript)。

我的index.html中的第一個腳本是

<script src="http://maps.google.com/maps/api/js?key=xxxxxx"></script>

在我的控制器中

        var geocoder = new google.maps.Geocoder();

        Object.keys(companies).forEach(function(key) 
        {
            var companyName = key;
            var comapnyLocation = companies[key];

          console.log('Key : ' + key + ', Value : ' + companies[key])

          geocoder.geocode( { 'address': comapnyLocation}, function(results, status) {
          if (status == 'OK') {
              console.log(results[0].geometry.location);
          } else {
            alert('Geocode was not successful for the following reason: ' + status);
          }
        });

在解碼器聲明之后的行上斷點時,我看到它是一個對象。 我斷點了回調的成功和失敗分支,並且只擊了OK分支。 但是,到那時,還沒有定義地址解析器。

我做錯了什么?

注意:我檢查了Google信息中心,並啟用了API。

它不起作用的原因是因為您正在嘗試盡早使用Google Maps API

根據文檔: https : //developers.google.com/maps/documentation/javascript/tutorial

async屬性可讓瀏覽器在加載Maps JavaScript API時呈現網站的其余部分。 API准備就緒后,它將調用使用callback參數指定的函數。


創建一個javascript函數,將其命名為任何名稱,然后在用於調用google maps api的腳本標簽中,添加以下參數:

&callback=YOUR_FUNCTION_NAME_HERE

 var map, geocode; var companies = { Google: '1600 Amphitheatre Parkway in Mountain View' }; function initMap(){ map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, zoom: 8 }); geocoder = new google.maps.Geocoder(); Object.keys(companies).forEach(function(key) { var companyName = key; var comapnyLocation = companies[key]; console.log('Key : ' + key + ', Value : ' + companies[key]) geocoder.geocode( { 'address': comapnyLocation}, function(results, status) { console.log("Results:", results ); if (status == 'OK') { console.log(results[0].geometry.location); } else { alert('Geocode was not successful for the following reason: ' + status); } }); }); } 
 <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"> </script> 

結果

在此處輸入圖片說明

首先,我對@CraigWayne表示歉意。 我確信他的回答會幫助其他人,但是由於我未能在問題中提供完整的信息,因此不能指望他給馬提供答案。

我正在AngularJs 1.x中進行編碼,並且正在使用NgMap

因此,當Craig建議等待地圖完全加載時,我懷疑NgMap的<map>指令可以解決此問題。

對我有用的-盡管我不知道如何-取代了

var geocoder = new google.maps.Geocoder();

geocoder.geocode( { 'address': comapnyLocation}, function(results, status) by

var url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' +  
            comapnyLocation +'&key=XXXX';

$http.get(url)

給出Craig指示的結果(在data.results )。

只是把它留在這里,以防將來對任何人有幫助。

暫無
暫無

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

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