gpt4 book ai didi

javascript - 如何在 Google map 上显示 2 个标记?

转载 作者:行者123 更新时间:2023-12-02 20:18:06 26 4
gpt4 key购买 nike

如何使用 Javascript API v3 在 Google map 上获取多个标记?下面,当我的代码添加第二个标记时,它删除第一个标记。

var locations = {
"1" : {
"name": "location1",
"address": "10000 N Scottsdale Rd",
"city": "Scottsdale",
"state": "AZ",
"zipcode": "85253"
},
"2" : {
"name": "location2",
"address": "15440 N 71st Street",
"city": "Scottsdale",
"state": "AZ",
"zipcode": "85254"
}
}
var geocoder = new google.maps.Geocoder();
for (item in locations) {
var loc = locations[item].address + ", " + locations[item].city + " " +
locations[item].state + " " + locations[item].zipcode;
geocoder.geocode( { 'address': loc}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var options = {
zoom: 10,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
}
if (map) {
new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: locations[item].name
});
} else {
var map = new google.maps.Map(document.getElementById("map"), options);
new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: locations[item].name
});
}
var infowindow = new google.maps.InfoWindow({ content: "test"});
} else { // if map lookup fails, display a map of phoenix
var phoenix = new google.maps.LatLng(33.4483771,-112.07403729999999);
var options = {
zoom: 11,
center: phoenix,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
}
map = new google.maps.Map(document.getElementById("map"), options);
}
});
}

最佳答案

map 变量仅在回调函数中定义(例如 function(results, status) {...}),因此当第二个地理编码点到来时返回后,您仍在创建一个新 map (第二次),因为该 map 尚未初始化。

您应该与标记添加代码分开声明和初始化 map 。

关于javascript - 如何在 Google map 上显示 2 个标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5952310/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com