我一直在尝试创建一个包含可点击标记的谷歌地图,缩放级别适应地图上的标记数量,我有以下代码,我知道这不太对,但可以&#39 ;弄清楚为什么,任何关于我出错的地方都会非常感激!
<script type="text/javascript">
function initialize() {
// My options
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
// Create map on #map_canva
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Define boundarys
var markerBounds = new google.maps.LatLngBounds();
// Create array
var countries = [
{title:'Theatre by the Lake', lat:54.32223562211788, lon:-2.742498400000045, content:"<h2>Theatre by the Lake</h2>"},
{title:'Pirelli International Rally', content:"<h2>Pirelli International Rally</h2>"},
{title:'Lowther Castle', content:"<h2>Lowther Castle</h2>"},
{title:'South Lakes Wild Animal Park', content:"<h2>South Lakes Wild Animal Park</h2>"},
{title:'Cumbria Karting', content:"<h2>Cumbria Karting</h2>"},
];
// Create markers
for (var i = 0; i < countries.length; i++) {
var c = countries[i];
c.marker = new google.maps.Marker({
position: new google.maps.LatLng(c.lat, c.lon),
map: map,
icon: '/display_images/icon_stockist.png',
title: c.title});
c.infowindow = new google.maps.InfoWindow({content: c.content});
google.maps.event.addListener(c.marker, 'click', makeCallback(c));
// Create marker bounds
markerBounds.extend(countries);
}
// Create info windows based on above content
function makeCallback(country) {
return function () {
country.infowindow.open(map, country.marker);
};
}
}
// Fit map to marker boundaries
map.fitBounds(markerBounds);
</script>
答案 0 :(得分:1)
您的问题是您在初始化函数中将map创建为局部变量,然后在调用map.fitBounds
时无法访问该函数,尝试使用该函数访问该函数。
使用initialize
声明地图,或在初始化函数中移动map.fitBounds()。
同样当你致电markerBounds.extend(countries);
时,你将它传递给你的整个国家/地区阵列,当你真正需要的是传递一个LatLng对象时。尝试这样的事情:
for (var i = 0; i < countries.length; i++) {
var c = countries[i];
var latlng = new google.maps.LatLng(c.lat, c.lon);
c.marker = new google.maps.Marker({
position: latlng,
map: map,
icon: '/display_images/icon_stockist.png',
title: c.title});
c.infowindow = new google.maps.InfoWindow({content: c.content});
google.maps.event.addListener(c.marker, 'click', makeCallback(c));
// Create marker bounds
markerBounds.extend(latlng);
}