[英]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.