【发布时间】:2021-07-22 10:21:39
【问题描述】:
我有一个包含位置数据的数组,其中一项是地址 - 即。 “加利福尼亚州旧金山市大街 123 号”。我想取那个地址,把它变成坐标,然后用这些坐标在地图上画一个标记。为此,我知道我需要使用geocode(),所以我将这部分添加到我的循环中。
如果我在数组中使用纬度和经度而不是地址,我可以让它正常工作。但是,由于我在循环中添加了geocode(),因此我只能获取数组中的第一个位置来显示标记。
我在这里看到了一些类似的问题,建议使用callback(),但我不明白。我还看到了一个建议,将 geocode() 延迟 0.5 秒,这对海报有效,但 cmets 表示它可能无法以较慢的互联网速度加载所有位置。
如何解决此问题以正确显示所有位置?
// Create the map with markers.
function createmap(zoomlevel, centerpos, showDot)
{
// Create the map canvas with options.
var map = new google.maps.Map(document.getElementById('map-canvas'), {
scrollwheel: false,
draggable: true,
mapTypeControl: false,
zoom: zoomlevel,
center: new google.maps.LatLng(40.577453, 2.237408), // Center the map at this location.
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker, i;
// For each location in the array...
for (i = 0; i < locations.length; i++)
{
// Get the coordintes for the address.
var geocoder = new google.maps.Geocoder();
var address = locations[i][5]; // ***This variable will output the address.***
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location_latitude = results[0].geometry.location.lat();
var location_longitude = results[0].geometry.location.lng();
// Create the map marker icon (SVG file).
var marker_icon = {
url: '//'+domain+'/__NEW__/_backend/assets/img/map-marker.svg',
anchor: new google.maps.Point(25,50),
scaledSize: new google.maps.Size(50,50)
}
// Place the marker on the map.
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location_latitude, location_longitude),
map: map,
icon: marker_icon
});
}
});
}
}
【问题讨论】:
-
回调是修复它的唯一方法
标签: javascript geocode gmaps.js