1

我需要 Google 地图方面的帮助。我想创建一个可以使用多个指针显示多个地址的地图。问题是所有地址都显示最后一个地址的指针图标。它可能与异步 geocoder.geocode 有关,但我是 JS 初学者,我无法解决这个问题。

有人可以帮忙吗?谢谢。

<html> 
<head> 
    <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
</head> 
<body>
<div id="map" style="width: 500px; height: 500px;"></div>

<script type="text/javascript">


var locations = [
    ['Place A', '2430 N 1060 E, North Logan, UT', 'A'],
    ['Place B', '495 W Jackson Street, Knoxville, IA', 'B'],
    ['Place C', '1900 N Flagler Drive, West Palm Beach, FL', 'C']
]; 


var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 0,
    center: new google.maps.LatLng(-33.92, 151.25),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});



var infowindow = new google.maps.InfoWindow();

var marker, i;


for (i = 0; i < locations.length; i++) {  


    var image = new google.maps.MarkerImage('http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + locations[i][2] + '|FF0000|000000',
        new google.maps.Size(21, 34),
        new google.maps.Point(0,0),
        new google.maps.Point(10, 34)
    );

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 
        'address': locations[i][1]
    }, function(results, status){

        if (status == google.maps.GeocoderStatus.OK) {

             marker = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map, 
                icon: image
            });
        } 
    });

}
</script>
</body>

4

1 回答 1

1

试试这个代码:

var marker, i;

for (i = 0; i < locations.length; i++) {  
  marker = createMarker(locations[i]);
}
function createMarker(location) {
  var image = new google.maps.MarkerImage('http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + location[2] + '|FF0000|000000',
        new google.maps.Size(21, 34),
        new google.maps.Point(0,0),
        new google.maps.Point(10, 34)
    );

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 
        'address': location[1]
    }, function(results, status){

        if (status == google.maps.GeocoderStatus.OK) {

             marker = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map, 
                icon: image
            });
        } 
    });
}
于 2012-11-12T19:36:19.817 回答