Google 地图使用自定义标签对地址进行地理编码

Google Maps geocode addressess with custom labels?

本文关键字:编码 地址 地图 自定义 标签 Google      更新时间:2023-09-26

过去一天左右我一直在用头撞桌子,但无法弄清楚这一点。每当将标记添加到我的地图时,它们都会随机生成标注。这很好,但是页面上调用了按列出的顺序显示位置的PHP代码。此列表必须与标记匹配。我想使用位置数组中的数字作为我的标签,但无论我尝试什么,我都无法让标签:位置[i][2](或任何变体)工作。

我尝试在 for 循环中添加一个等于位置 [i][2] 的变量,但它只是在标记函数中调用变量时存储并显示最后一个数字。

希望这是有道理的。

  var locations = [
  ['text','address1','1'], 
  ['text','address2','2'],
  ];
var labels = '123456789';
var labelIndex = 0;
var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 10,
  center: new google.maps.LatLng(38.3509665,-81.6881185),
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  disableDefaultUI: true
});
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
var infowindow = new google.maps.InfoWindow();
var geocoder = new google.maps.Geocoder();
var marker, i;
for (i = 0; i < locations.length; i++) {
  geocodeAddress(locations[i]);
}
function geocodeAddress(location) {
geocoder.geocode( { 'address': location[1]}, function(results, status) {
//alert(status);
if (status == google.maps.GeocoderStatus.OK) {
  //alert(results[0].geometry.location);
  map.setCenter(results[0].geometry.location);
  createMarker(results[0].geometry.location,location[0]+"<br>"+location[1]);
}
else
{
  alert("some problem in geocode" + status);
}
 }); 
}
function createMarker(latlng,html){
var marker = new google.maps.Marker({
position: latlng,
map: map,
label: labels[labelIndex++ % labels.length],
}); 
google.maps.event.addListener(marker, 'mouseover', function() { 
infowindow.setContent(html);
infowindow.open(map, marker);
});
google.maps.event.addListener(marker, 'mouseout', function() { 
infowindow.close();
});
}
google.maps.event.addDomListener(window, 'load', initialize);

提前谢谢。

这是更新的函数,我为createMarker添加了第三个变量,称为 label location[2]传递给这个变量。

function geocodeAddress(location) {
geocoder.geocode( { 'address': location[1]}, function(results, status) {
//alert(status);
if (status == google.maps.GeocoderStatus.OK) {
  //alert(results[0].geometry.location);
  map.setCenter(results[0].geometry.location);
  createMarker(results[0].geometry.location,location[0]+"<br>"+location[1],location[2]);
}
else
{
  alert("some problem in geocode" + status);
}
 }); 
}
function createMarker(latlng,html,label){
var marker = new google.maps.Marker({
position: latlng,
map: map,
label: label
});