如何在Google地图上显示2个标记?

时间:2011-05-10 15:13:27

标签: javascript google-maps

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

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);
        }
    });
}

2 个答案:

答案 0 :(得分:1)

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

您应该从添加代码的标记中单独声明和初始化地图。

答案 1 :(得分:1)

从数据集中循环标记构造。您集合中的每个项目都会像往常一样创建标记。仅对地图进行一次实例化,并在标记创建中使用分配给它的变量。