我不明白如何设置地图边界。我查看了其他几个相关问题,但我无法让它们正常工作。
这就是我正在尝试的:http: //jsfiddle.net/ZFyDY/
在每个标记之后,我调整地图的边界,如下所示:
var bounds = new google.maps.LatLngBounds();
bounds.extend(gps_coords);
我究竟做错了什么?
我不明白如何设置地图边界。我查看了其他几个相关问题,但我无法让它们正常工作。
这就是我正在尝试的:http: //jsfiddle.net/ZFyDY/
在每个标记之后,我调整地图的边界,如下所示:
var bounds = new google.maps.LatLngBounds();
bounds.extend(gps_coords);
我究竟做错了什么?
不要每次都创建一个新的空边界对象(对于每个标记),在开始时创建一个,将所有点添加到它,然后使用它来缩放和居中地图。
代码片段:
function map_init() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var bounds = new google.maps.LatLngBounds();
// Add GPS location
/*
var sensor_image = new google.maps.MarkerImage("#{asset_path "
sensor.png "}",
new google.maps.Size(38, 38),
new google.maps.Point(0, 0),
new google.maps.Point(19, 19));
*/
if (navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
var gps_coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
new google.maps.Marker({
position: gps_coords,
map: map,
// icon: sensor_image
});
var bounds = new google.maps.LatLngBounds();
bounds.extend(gps_coords);
}, function() {
// Handle no geolocation support
})
}
//Add Store location
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': "New York, NY"
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var store_coords = results[0].geometry.location;
new google.maps.Marker({
position: store_coords,
animation: google.maps.Animation.DROP,
map: map
});
bounds.extend(store_coords);
map.fitBounds(bounds);
}
});
geocoder.geocode({
'address': "Boston, MA"
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var store_coords = results[0].geometry.location;
new google.maps.Marker({
position: store_coords,
animation: google.maps.Animation.DROP,
map: map
});
bounds.extend(store_coords);
map.fitBounds(bounds);
}
});
//Configure map
//bounds.extend(gps_coords);
//bounds.extend(store_coords);
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window,'load', map_init)
html,
body,
#map_canvas {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>