我为我的Rails应用编写了一个代码,使用以下代码在Google地图上显示一些位置:
var myOptions = {
zoom: 2,
center: new google.maps.LatLng(71.1333,27.7000, 13), // **I need to set the center from the locations in here.**
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#search_map_canvas')[0], myOptions);
var addresses = <%=raw search_offering_addressess.to_json %>;
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
new google.maps.Marker({
position: latlng,
map: map
});
});
}
此处,search_offering_addressess
包含一系列位置。例如。 [&#34;柏林,德国&#34;,&#34;苏黎世,瑞士&#34;,....]
如何找到该位置的中点?我的地图错过了一些位置标记。
答案 0 :(得分:0)
使用LatLngBounds
尝试此操作 //newly added
var bounds = new google.maps.LatLngBounds();
var myOptions = {
zoom: 2,
center: new google.maps.LatLng(71.1333,27.7000, 13), // **I need to set the center from the locations in here.**
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#search_map_canvas')[0], myOptions);
var addresses = <%=raw search_offering_addressess.to_json %>;
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
//newly added
bounds.extend(latlng);
new google.maps.Marker({
position: latlng,
map: map
});
});
}
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);