我将 Google map 与我们的 CMS 搜索工具一起使用,并且根据搜索在列表和 Google map 上成功返回了一组商店。但我似乎无法工作的是 map 自动设置缩放并将所有返回标记放入 map 中。我看过很多其他关于做类似事情的帖子,但似乎都与 map API v2 相关。这就是我尝试设置缩放和适合的内容。
var iconBase = '/img/';
var icons = {
parent: {
icon: iconBase + 'parent.png'
},
child: {
icon: iconBase + 'child.png'
}
}
var locations = [
{exp:low_search:results query="{segment_3}" backspace="1"}
["{title}", {latitude}, {longitude}, "{type}", "<p>{street_address}<br> {city}<br> {zip}</p>", "{website}" ],
{/exp:low_search:results}
];
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var markerBounds = new google.maps.LatLngBounds();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: locations[i][3] == "Yes" ? '/img/parent.png' : '/img/child.png',
address: locations[i][4]
});
markerBounds.extend(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent('<h2>' + locations[i][0] + '</h2>' + this.address + '<p><a href="' + locations[i][5] + '">website</a>');
infowindow.open(map, marker);
};
})(marker, i));
}
map.fitBounds(markerBounds);
我哪里失败了?
澄清一下,当我删除标记边界和拟合边界时,我就会看到工作 map 。控制台似乎在 markerBounds.extend(marker);
最佳答案
很容易错过。您正在给予markerBounds.extend()
一个标记对象,但它实际上需要一个 google.maps.LatLng
目的。
试试这个:
var marker, i, markerLatLng;
for (i = 0; i < locations.length; i++) {
if (locations[i].length > 0) {
markerLatLng = new google.maps.LatLng(locations[i][1], locations[i][2]);
} else {
markerLatLng = new google.maps.LatLng(37.778190, -122.420434);
}
marker = new google.maps.Marker({
position: markerLatLng,
map: map,
icon: locations[i][3] == "Yes" ? '/img/parent.png' : '/img/child.png',
address: locations[i][4]
});
markerBounds.extend(markerLatLng);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent('<h2>' + locations[i][0] + '</h2>' + this.address + '<p><a href="' + locations[i][5] + '">website</a>');
infowindow.open(map, marker);
};
})(marker, i));
}
map.fitBounds(markerBounds);
我声明了一个新变量,它的值是 google.maps.LatLng
在 for 循环中分配给它的对象,然后将其传递到 markerBounds.extend()
方法。
关于javascript - 从结果集中自动设置 Google map 缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29095640/