How would one calculate the zoom of a map, based on miles input is given?
An example would be that the user selects from a drop-down that they want to search within a 50 miles radius. The map zoom level should update to show 50 miles area around the original coordinates given in the map.
My attempt which is as inaccurate and amature as it can be...
calculateZoomLevel(miles) {
let zoom = 11;
switch(miles) {
case 5 : {
zoom = 14;
break;
}
case 15 : {
zoom = 13;
break;
}
case 25 : {
zoom = 11;
break;
}
case 50 : {
zoom = 10;
break;
}
case 100 : {
zoom = 8;
break;
}
case 3963.2 : {
zoom = 1
}
}
return zoom;
}
Simplest option is to create a google.maps.Circle
object with your desired radius, then fit the map to its bounds (you don't need to actually show the circle on the map if you don't want it).
var radius = parseInt(document.getElementById('radius').value, 10) * 1609.34;
circle = new google.maps.Circle({
center: map.getCenter(),
radius: radius,
fillOpacity: 0.35,
fillColor: "#FF0000",
map: map
});
live example of a "radius search"
proof of concept fiddle (uses the geocoder to set the map center per the address entered
map.fitBounds(circle.getBounds());
code snippet:
// global "map" variable
var map = null;
var circle = null;
var geocoder = new google.maps.Geocoder();
function initialize() {
// create the map
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(43.907787, -79.359741),
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
function codeAddress() {
var address = document.getElementById('address').value;
var radius = parseInt(document.getElementById('radius').value, 10) * 1609.34;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
side_bar_html = "";
map.setCenter(results[0].geometry.location);
var searchCenter = results[0].geometry.location;
if (circle) circle.setMap(null);
circle = new google.maps.Circle({
center: searchCenter,
radius: radius,
fillOpacity: 0.35,
fillColor: "#FF0000",
map: map
});
map.fitBounds(circle.getBounds());
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
html,
body {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
}
#map_canvas {
height: 90%;
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>
<div>
<input id="address" type="textbox" value="Toronto">
<input type="button" value="Geocode" onclick="codeAddress()"><br>
<input id="radius" type="textbox" value="50"> miles
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With