2012-09-05 39 views
3

在一個頁面上顯示多個實體。對於每個實體都有一個谷歌地圖。這是我怎麼收拾顯示地圖只有一個實體:在一頁上顯示多個谷歌地圖

var map; 
var geocoder; 

$(document).ready(function(){ 
    google.maps.event.addDomListener(window, 'load', initialize); 
}); 

function initialize() { 
    geocoder = new google.maps.Geocoder(); 
    var mapOptions = { 
     zoom: 16, 
     center: new google.maps.LatLng(50.317408,11.12915), 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 
    map = new google.maps.Map(document.getElementById('map_canvas'), 
     mapOptions); 
     codeAddress($('#entityID span#address').text()); 
} 

function codeAddress(address) { 

    geocoder.geocode({ 
     'address': address 
    }, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      map.setCenter(results[0].geometry.location); 
      var marker = new google.maps.Marker({ 
       map: map, 
       position: results[0].geometry.location 
      }); 
     } else { 
      codeAddress('germany'); 
     } 
    }); 
} 

現在我想顯示多個地圖,每一個不同的位置。那看起來怎麼樣?有任何想法嗎?該算法應該能夠處理動態數量的實體。

回答

6

製作地圖的數組,這樣的:

var maps = []; // array for now 
var geocoder; 

$(document).ready(function(){ 
    google.maps.event.addDomListener(window, 'load', initialize('map_1')); // two calls 
    google.maps.event.addDomListener(window, 'load', initialize('map_2')); 
}); 

function initialize(_id) { // Map id for future manipulations 
    geocoder = new google.maps.Geocoder(); 
    var mapOptions = { 
     zoom: 16, 
     center: new google.maps.LatLng(50.317408,11.12915), 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 
    maps[_id] = new google.maps.Map(document.getElementById('map_canvas_'+_id), // different containers 
     mapOptions); 
     codeAddress($('#entityID span#address').text()); 
} 

function codeAddress(address, map_id) { 

    geocoder.geocode({ 
     'address': address 
    }, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      map.setCenter(results[0].geometry.location); 
      var marker = new google.maps.Marker({ 
       map: maps[map_id], // target nedded map by second parametr 
       position: results[0].geometry.location 
      }); 
     } else { 
      codeAddress('germany'); 
     } 
    }); 
} 
+0

你是什麼「的第二個參數//目標所需的地圖」,其中第二個參數是什麼意思? – inquisitive

+0

看起來像拼錯:) –