Reputation: 525
I have a script for google maps that has zoom
set at a certain distance for desktop browsers. I was wondering if there's away to have a different zoom when being viewed on mobile device.
I think it can be done with a if
statement but I'm not sure how I would integrate it into the script. I'm not that comfortable with jquery and would appreciate any help.
script is:
<script>
window.onload = function () {
var latlng = new google.maps.LatLng(51.523612, -0.125816);
var styles = [{
"stylers": [{
"saturation": -100
}, {
"hue": "#ff0000"
}, {
"gamma": 0.92
}]
}, {
"featureType": "poi",
"stylers": [{
"visibility": "off"
}]
}, {
"elementType": "geometry.fill",
"stylers": [{
"gamma": 0.85
}]
}, {}]
var myOptions = {
zoom: 17,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: false,
draggable: false,
styles: styles
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
});
marker.setMap(map);
}
</script>
Upvotes: 3
Views: 3797
Reputation: 17511
You are working with a fixed center (51.523612, -0.125816)
, andd a fixed zoom (17)
so your map will always display as if you told it
map.setCenter(new google.maps.LatLng(51.523612, -0.125816));
map.setZoom(17);
In my screen (1920x1080) with console open, this will roughly mean that the map bounds are defined by
SW:(51.522, -0.136)
NE:(51.526, -0.12)
So I can achieve the same viewport if I instead of setting the center and zoom, I tell my map to fit those bounds.
map.fitBounds(new google.maps.LatLngBounds(new google.maps.LatLng(51.522, -0.136), new google.maps.LatLng(51.526, -0.12)))
And that will automatically calculate which zoom it should apply given your screen size. Of course, zoom changes in discrete steps, so the result might not be exactly what you need to show.
In your case, this means to declare your map as
var myOptions = {
bounds: new google.maps.LatLngBounds(new google.maps.LatLng(51.522, -0.136), new google.maps.LatLng(51.526, -0.12)),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: false,
draggable: false,
styles: styles
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
Upvotes: 5