问题
I have used google maps for displaying some locations using markers, based on the user's current location. User's current location is the center point of the map. The default zoom level is 12. In default, I displayed markers within 300 miles(approximately in my case) distance only.
In that how can I do the following,
1) If decrease the zoom level, I need to increase the distance that should display markers within the increased distance also. how much distance should I increase in miles (i.e. Zoom level is 11) ?
2) If increase the zoom level, I need to decrease the distance that should display markers without the increased distance. how much distance should I decrease in miles (i.e. Zoom level is 13) ?
Please suggest me there is any built-in option to do that ...
回答1:
I'm not sure if I understand your question correctly, but when you increase the zoom by 1 you must divide the distance by 2. When you decrease the zoom by 1 you must multiply the distance by 2.
The formula would be:
newDistance=(Math.pow(2,initialZoom-currentZoom)*initialDistanceAtInitialZoom)
Demo: (drawing a circle where the formula above will be used to calculate the radius)
function initialize() {
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 4,
minZoom:2,
center: new google.maps.LatLng(52.52, 13.4),
noClear:true,
zoomControl:true,
draggable:false,
scrollwheel:false,
disableDefaultUI:true
}),
circle = new google.maps.Circle({
map:map,
center:map.getCenter(),
radius:300000*1.609344
}),
ctrl = document.getElementById('radius');
map.controls[google.maps.ControlPosition.TOP_CENTER].push(ctrl);
google.maps.event.addListener(map,'zoom_changed',
(function(z,r){
return function(){
var radius=(Math.pow(2,z-map.getZoom())*r);
circle.setRadius(radius);
ctrl.innerHTML=(radius/1609.344).toFixed(3)+' miles(zoom:'+map.getZoom()+')';
}
}(map.getZoom(),circle.getRadius())
));
google.maps.event.trigger(map,'zoom_changed');
}
google.maps.event.addDomListener(window, 'load', initialize);
html,body,#map_canvas{
height:100%;
margin:0;
padding:0;
}
#radius{
background:#fff;
padding:4px;
font-size:14px;
font-family:Monospace;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map_canvas"><div id="radius"></div></div>
回答2:
I found the zoom_changed event after a quick google
ex:
map.addListener('zoom_changed', function() {
infowindow.setContent('Zoom: ' + map.getZoom());
});
more info Google Api Docs here
来源:https://stackoverflow.com/questions/32284554/google-maps-distance-based-on-the-zoom-level