Google Maps V3 - Load different markers on click function - google-maps

So I have the following in my HTML which represents regions in the UK:-
<h4 id="google-ne" class="active">The North East</h4>
<h4 id="google-nw">The North West</h4>
<h4 id="google-ea">East Anglia</h4>
<h4 id="google-em">East Midlands</h4>
<h4 id="google-tm">The Midlands</h4>
<h4 id="google-wm">West Midlands</h4>
<h4 id="google-ld">London</h4>
<h4 id="google-se">South East</h4>
<h4 id="google-sw">South West</h4>
<h4 id="google-ws">Wales</h4>
<h4 id="google-sl">Scotland</h4>
and then the marker lat / long and region are displayed in HTML as follows:-
<div class="marker" data-lat="52.559437" data-lng="-2.1493073" data-region="West Midlands"></div>
<div class="marker" data-lat="51.646145" data-lng="-0.45614472" data-region="South East"></div>
and so on, there are about 400 markers.
I am currently using the following code to display all markers on the map which is working fine:-
var center = new google.maps.LatLng(51.5280359,-0.1304897);
function initialize_map() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
var markerBounds = new google.maps.LatLngBounds();
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var isDraggable = w > 480 ? true : false;
var mapOptions = {
zoom: 8,
center: center,
//draggable: isDraggable,
//mapTypeControl: false,
//draggable: false,
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
scrollwheel: true,
navigationControl: true,
streetViewControl: true,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
// Multiple Markers
// Loop through our array of markers & place each one on the map
$('.marker').each(function() {
var location = {
latLng: new google.maps.LatLng(
$( this ).data( 'lat' ),
$( this ).data( 'lng' )
),
//title: $( this ).find( 'h2' ).html()
};
new google.maps.Marker( {
map: map,
position: location.latLng,
//title: $( this ).data( 'desc' )
} );
markerBounds.extend( location.latLng );
});
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
var styles = [
/* Black & White {"featureType":"water","elementType":"geometry","stylers":[{"color":"#e9e9e9"},{"lightness":17}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"color":"#f5f5f5"},{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#ffffff"},{"lightness":17}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#ffffff"},{"lightness":29},{"weight":0.2}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#ffffff"},{"lightness":18}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#ffffff"},{"lightness":16}]},{"featureType":"poi","elementType":"geometry","stylers":[{"color":"#f5f5f5"},{"lightness":21}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#dedede"},{"lightness":21}]},{"elementType":"labels.text.stroke","stylers":[{"visibility":"on"},{"color":"#ffffff"},{"lightness":16}]},{"elementType":"labels.text.fill","stylers":[{"saturation":36},{"color":"#333333"},{"lightness":40}]},{"elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"geometry","stylers":[{"color":"#f2f2f2"},{"lightness":19}]},{"featureType":"administrative","elementType":"geometry.fill","stylers":[{"color":"#fefefe"},{"lightness":20}]},{"featureType":"administrative","elementType":"geometry.stroke","stylers":[{"color":"#fefefe"},{"lightness":17},{"weight":1.2}]} */
/* Colour*/ {"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"saturation":"-63"},{"lightness":"23"}]},{"featureType":"landscape.natural","elementType":"geometry.fill","stylers":[{"saturation":"-100"},{"lightness":"25"}]},{"featureType":"landscape.natural.terrain","elementType":"geometry.fill","stylers":[{"saturation":"0"}]},{"featureType":"poi.park","elementType":"geometry.fill","stylers":[{"saturation":"0"},{"color":"#95bf97"},{"lightness":"59"}]},{"featureType":"poi.school","elementType":"geometry.fill","stylers":[{"lightness":"5"},{"hue":"#ff0000"},{"saturation":"-100"}]},{"featureType":"poi.sports_complex","elementType":"geometry.fill","stylers":[{"lightness":"5"},{"saturation":"-100"}]},{"featureType":"road.local","elementType":"geometry.fill","stylers":[{"saturation":"-85"},{"lightness":"12"}]}
];
map.setOptions({styles: styles});
}
initialize_map();
}
What I want to do now is on click of say 'West Midlands' #google-wm, it removes all markers currently on the map and then only shows markers where the data-region == 'West Midlands'
How is it possible to do this?
Thanks in advance.

You could do something like that. Code is commented for the parts that I have added/changed.
var markers = [];
var map;
function initialize() {
var myLatLng = new google.maps.LatLng(52, -1);
var mapOptions = {
zoom: 6,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
$('.marker').each(function() {
var location = {
latLng: new google.maps.LatLng(
$(this).data('lat'),
$(this).data('lng')
),
};
var marker = new google.maps.Marker({
map: map,
position: location.latLng,
});
// Register click event
$(this).on('click', function() {
clickMarker($(this).data('region'));
});
// Push marker and region to markers array
markers.push({
'marker': marker,
'region': $(this).data('region')
});
});
}
function clickMarker(region) {
// Loop through markers array
for (var i = 0; i < markers.length; i++) {
// If marker region = selected region, display it
if (markers[i].region === region) {
markers[i].marker.setMap(map);
} else {
// Hide marker from different region
markers[i].marker.setMap(null);
}
}
}
initialize();
#map-canvas {
height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="map-canvas"></div>
<div class="marker" data-lat="52.5" data-lng="-2.1" data-region="West Midlands">Marker 1 - WM</div>
<div class="marker" data-lat="52.6" data-lng="-2.2" data-region="West Midlands">Marker 2 - WM</div>
<div class="marker" data-lat="51.6" data-lng="-0.4" data-region="South East">Marker 3 - SE</div>
<div class="marker" data-lat="51.7" data-lng="-0.5" data-region="South East">Marker 4 - SE</div>
<script src="https://maps.googleapis.com/maps/api/js"></script>

Related

Showing a point on GoogleMaps after clicking a button

I have Google Maps with many markers.
This is my code:
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding_all_2">
<div class="apartament_atrakcje">Atrakcja 1 pl</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding_all_2">
<div class="apartament_atrakcje">Atrakcja 2 PL</div>
</div>
<div id="map_canvas"></div>
<script>
window.onload = function () {
var styles = [{"featureType":"all"}];
var bounds = new google.maps.LatLngBounds();
var options = {
mapTypeControlOptions: {
mapTypeIds: ['Styled']
},
center: new google.maps.LatLng(11, 22),
zoom: 15,
disableDefaultUI: true,
mapTypeId: 'Styled'
};
marker = new google.maps.Marker({
map:map,
});
var div = document.getElementById('map_canvas');
var map = new google.maps.Map(div, options);
var styledMapType = new google.maps.StyledMapType(styles, { name: 'Styled' });
var markers = [
['Atrakcja 1 pl', 51.73925413, 19.51309225, 'Atrakcja 1 pl', '#', 'poi.png'],
['Atrakcja 2 PL', 53.41475000, 14.60220358, 'Atrakcja 2 PL', '#', 'poi.png'],
['Biskupia', 51.93780943, 15.52505514, 'Biskupia', '#', 'poi2.png']
];
var infoWindow= new google.maps.InfoWindow({maxWidth:600}),
marker, i,
image = 'http://localhost/apartamenty/assets/poi.png';
for( i = 0; i < markers.length; i++ ) {
var beach = markers[i];
var position = new google.maps.LatLng(beach[1], beach[2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
icon: 'http://localhost/apartamenty/assets/' + beach[5],
title: beach[0],
myurl: beach[4]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(''+marker['title']+'');
infoWindow.open(map, marker);
}
})(marker, i));
map.fitBounds(bounds);
map.mapTypes.set('Styled', styledMapType);
}
}
</script>
I have a map and the markers on it. This is ok!
After clicking on link obj-1 or obj-2 I would like to:
- center the map on this one, selected marker
- display the marker of this marker
If the user clicks on the link "Atrakcja 1 pl" - then map is center on marker with title Atrakcja 1 pll and his hint would be visible.
Does anyone know how to do it in my code?
One option would be to keep references to the markers in an array and add DOM click listeners to your "links" to open the marker's InfoWindow and center the map on that marker.
create an array of markers:
var gmarkers=[];
for (i = 0; i < markers.length; i++) {
var beach = markers[i];
var position = new google.maps.LatLng(beach[1], beach[2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
// icon: 'http://localhost/apartamenty/assets/' + beach[5],
title: beach[0],
myurl: beach[4]
});
gmarkers.push(marker);
// ...
add click listeners to your "links" that opens that marker's InfoWindow and centers the map on its position:
if (document.getElementById('obj-'+(i+1))) {
// relies on the naming convention in your posted code
google.maps.event.addDomListener(document.getElementById('obj-'+(i+1)), 'click', function(i) {
return function() {
google.maps.event.trigger(gmarkers[i], 'click');
map.setCenter(gmarkers[i].getPosition());
}}(i))
}
proof of concept fiddle
code snippet:
html,
body,
#map_canvas {
height: 90%;
width: 100%;
padding: 0px;
margin: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding_all_2">
<a href="#" class="obj-1" id="obj-1">
<div class="apartament_atrakcje">Atrakcja 1 pl</div>
</a>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding_all_2">
<a href="#" class="obj-2" id="obj-2">
<div class="apartament_atrakcje">Atrakcja 2 PL</div>
</a>
</div>
<div id="map_canvas"></div>
<script>
window.onload = function() {
var styles = [{
"featureType": "all"
}];
var gmarkers = [];
var bounds = new google.maps.LatLngBounds();
var options = {
mapTypeControlOptions: {
mapTypeIds: ['Styled']
},
center: new google.maps.LatLng(11, 22),
zoom: 15,
disableDefaultUI: true,
mapTypeId: 'Styled'
};
marker = new google.maps.Marker({
map: map,
});
var div = document.getElementById('map_canvas');
var map = new google.maps.Map(div, options);
var styledMapType = new google.maps.StyledMapType(styles, {
name: 'Styled'
});
var markers = [
['Atrakcja 1 pl', 51.73925413, 19.51309225, 'Atrakcja 1 pl', '#', 'poi.png'],
['Atrakcja 2 PL', 53.41475000, 14.60220358, 'Atrakcja 2 PL', '#', 'poi.png'],
['Biskupia', 51.93780943, 15.52505514, 'Biskupia', '#', 'poi2.png']
];
var infoWindow = new google.maps.InfoWindow({
maxWidth: 600
}),
marker, i,
image = 'http://localhost/apartamenty/assets/poi.png';
for (i = 0; i < markers.length; i++) {
var beach = markers[i];
var position = new google.maps.LatLng(beach[1], beach[2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
// icon: 'http://localhost/apartamenty/assets/' + beach[5],
title: beach[0],
myurl: beach[4]
});
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent('' + marker['title'] + '');
infoWindow.open(map, marker);
}
})(marker, i));
map.fitBounds(bounds);
map.mapTypes.set('Styled', styledMapType);
if (document.getElementById('obj-' + (i + 1))) {
// relies on the naming convention in your posted code
google.maps.event.addDomListener(document.getElementById('obj-' + (i + 1)), 'click', function(i) {
return function() {
google.maps.event.trigger(gmarkers[i], 'click');
map.setCenter(gmarkers[i].getPosition());
}
}(i))
}
}
}
</script>

Google Map - Getting co-ords out

<Body>
<!--Button to pull out marker co-ords-->
<p><button onclick="document.getElementById('latlnginpara').innerHTML = map.marker.getBounds()">Get map bounds</button></p>
<!--This is where the co-ords will sit for now-->
<div id="latlnginpara"></div>
<!--This plots a slot for the map-->
<div id="map" style="width:100%;height:500px;"></div>
<!--Now starts the Map fun-->
<script>
function myMap() {
var mapCanvas = document.getElementById("map");
var myCenter=new google.maps.LatLng(51.508742,-0.120850);
var mapOptions = {
center: myCenter,
zoom: 5,
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
streetViewControl: true,
overviewMapControl: true,
rotateControl: true,
};
var map = new google.maps.Map(mapCanvas, mapOptions);
//1 marker bit
var marker;
function placeMarker(location) {
if ( marker ) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map
});
}
}
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD5WIxyWvYfFU3vY27DM7mc-JClPwPLB0A&callback=myMap"></script>
</Body>
For the life of me, I'm trying to get co-ordinates OUT of google maps from a marker, for later use in a database......
I have most of the code but I can't seem to get it to work together!
This super brain helped someone get 1 marker that updates
GoogleMaps v3 API Create only 1 marker on click
This code pulled out co-ordinates into the body of the page.
https://www.w3schools.com/graphics/tryit.asp?filename=trymap_ref_getbounds
But all together....
Your help would be much appreciated!!!
You can simply get the marker's coordinates using .lat() and .lng().
var marker, map;
function placeMarker(location) {
if (marker) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map
});
}
document.getElementById('location').textContent = location.toString();
document.getElementById('lat').textContent = location.lat(); // get latitude
document.getElementById('lng').textContent = location.lng(); // get longitude
}
function myMap() {
var mapCanvas = document.getElementById("map");
var myCenter = new google.maps.LatLng(51.508742, -0.120850);
var mapOptions = {
center: myCenter,
zoom: 5,
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
streetViewControl: true,
overviewMapControl: true,
rotateControl: true,
};
map = new google.maps.Map(mapCanvas, mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
myMap();
<!--Button to pull out marker co-ords-->
<p><button onclick="document.getElementById('latlnginpara').innerHTML = map.marker.getBounds()">Get map bounds</button></p>
<p id='location'></p>
<p id='lat'></p>
<p id='lng'></p>
<!--This is where the co-ords will sit for now-->
<div id="latlnginpara"></div>
<!--This plots a slot for the map-->
<div id="map" style="width:100%;height:500px;"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD5WIxyWvYfFU3vY27DM7mc-JClPwPLB0A&"></script>
Many thanks! This is the answer
var marker, map;
function placeMarker(location) {
if (marker) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map
});
}
document.getElementById('location').textContent = location.toString();
document.getElementById('lat').textContent = location.lat(); // get latitude
document.getElementById('lng').textContent = location.lng(); // get longitude
}
function myMap() {
var mapCanvas = document.getElementById("map");
var myCenter = new google.maps.LatLng(51.508742, -0.120850);
var mapOptions = {
center: myCenter,
zoom: 5,
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
streetViewControl: true,
overviewMapControl: true,
rotateControl: true,
};
map = new google.maps.Map(mapCanvas, mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
myMap();
<!--Button to pull out marker co-ords-->
<p><button onclick="document.getElementById('latlnginpara').innerHTML = map.marker.getBounds()">Get map bounds</button></p>
<p id='location'></p>
<p id='lat'></p>
<p id='lng'></p>
<!--This is where the co-ords will sit for now-->
<div id="latlnginpara"></div>
<!--This plots a slot for the map-->
<div id="map" style="width:100%;height:500px;"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD5WIxyWvYfFU3vY27DM7mc-JClPwPLB0A&"></script>

how to calculate the number of marker inside manually drawn polygon on google map

I have a map where there can be n number of marker plotted on the google map, when the user draw the polygon on the map I need to know the makers plotted inside the polygon.
I tried to draw the polygon on the map which is as shown below
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"> </script>
<style>
html,body{height:100%;margin:0}
#map_canvas{height:90%;}
</style>
<script>
function initialize() {
var myLatLng = {lat: 52.5498783, lng: 13.425209099999961};
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(52.5498783, 13.425209099999961),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
google.maps.event.addDomListener(map.getDiv(),'mousedown',function(e){
//do it with the right mouse-button only
if(e.button!=2)return;
//the polygon
poly=new google.maps.Polyline({map:map,clickable:false});
//move-listener
var move=google.maps.event.addListener(map,'mousemove',function(e){
poly.getPath().push(e.latLng);
});
//mouseup-listener
google.maps.event.addListenerOnce(map,'mouseup',function(e){
google.maps.event.removeListener(move);
var path=poly.getPath();
poly.setMap(null);
poly=new google.maps.Polygon({map:map,path:path});
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
Use the right mouse-button to draw an overlay<br/>
<div id="map_canvas"></div>
</body>
</html>
use right mouse button to draw
for now I have only one marker, how to find the number of markers inside the polygon and their latitude and longitude the polygons can be of any shape on the map.
You could utilize containsLocation() function to determine whether marker is located inside a polygon or not.
This example draws a green polygon when the marker falls outside of the specified polygon, and a red polygon when the marker falls inside the polygon.
function initialize() {
var myLatLng = { lat: 52.5498783, lng: 13.425209099999961 };
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(52.5498783, 13.425209099999961),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
google.maps.event.addDomListener(map.getDiv(), 'mousedown', function (e) {
//do it with the right mouse-button only
if (e.button != 2) return;
//the polygon
var poly = new google.maps.Polyline({ map: map, clickable: false });
//move-listener
var move = google.maps.event.addListener(map, 'mousemove', function (e) {
poly.getPath().push(e.latLng);
});
//mouseup-listener
google.maps.event.addListenerOnce(map, 'mouseup', function (e) {
google.maps.event.removeListener(move);
var path = poly.getPath();
poly.setMap(null);
poly = new google.maps.Polygon({ map: map, path: path });
var resultColor = google.maps.geometry.poly.containsLocation(marker.getPosition(), poly) ? 'green' : 'red';
poly.setOptions({ fillColor: resultColor, strokeOpacity: 0.5 });
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html, body {
height: 100%;
margin: 0;
}
#map_canvas {
height: 90%;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?&libraries=geometry"> </script>
Use the right mouse-button to draw an overlay<br />
<div id="map_canvas"></div>
To get the number of markers inside the polygon, one option is to keep references to them in array, then iterate through that array checking to see if the marker is in the polygon or not. To determine if a marker is inside the polygon, the geometry library poly namespace method containsLocation can be used:
var markerCnt = 0;
for (var i = 0; i < markers.length; i++) {
if (google.maps.geometry.poly.containsLocation(markers[i].getPosition(), poly)) {
markerCnt++;
}
}
document.getElementById('numberMarkers').innerHTML += "There are " + markerCnt + " markers in the polygon<br>";
proof of concept fiddle
code snippet:
var markers = [];
function initialize() {
var myLatLng = {
lat: 52.5498783,
lng: 13.425209099999961
};
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(52.5498783, 13.425209099999961),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
markers.push(marker);
google.maps.event.addListener(map, 'bounds_changed', makeRandomMarkers);
var poly;
google.maps.event.addDomListener(map.getDiv(), 'mousedown', function(e) {
//do it with the right mouse-button only
if (e.button != 2) return;
//the polygon
if (poly && poly.setMap) {
poly.setMap(null);
}
poly = new google.maps.Polyline({
map: map,
clickable: false
});
//move-listener
var move = google.maps.event.addListener(map, 'mousemove', function(e) {
poly.getPath().push(e.latLng);
});
//mouseup-listener
google.maps.event.addListenerOnce(map, 'mouseup', function(e) {
google.maps.event.removeListener(move);
var path = poly.getPath();
poly.setMap(null);
poly = new google.maps.Polygon({
map: map,
path: path
});
var markerCnt = 0;
for (var i = 0; i < markers.length; i++) {
if (google.maps.geometry.poly.containsLocation(markers[i].getPosition(), poly)) {
markerCnt++;
}
}
document.getElementById('numberMarkers').innerHTML = "There are " + markerCnt + " markers in the polygon<br>";
});
});
}
function getRandom(min, max) {
return Math.random() * (max - min + 1) + min;
}
google.maps.event.addDomListener(window, 'load', initialize);
function makeRandomMarkers() {
var bounds = map.getBounds();
var maxLat = bounds.getNorthEast().lat(); // 70;
var minLat = bounds.getSouthWest().lat(); // 37;
var maxLong = bounds.getNorthEast().lng(); // 50;
var minLong = bounds.getSouthWest().lng(); // -8;
for (var j = 0; j < 50; j++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(getRandom(minLat, maxLat),
getRandom(minLong, maxLong)),
map: map
});
markers.push(marker);
}
}
html,
body {
height: 100%;
margin: 0
}
#map_canvas {
height: 90%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
Use the right mouse-button to draw an overlay
<br/>
<div id="numberMarkers"></div>
<div id="map_canvas"></div>

Google Maps - single map marker with fitBounds [duplicate]

Here is the code I have written to add a marker to the google map by providing latitude and longitude. The problem is that I get a very highly zoomed google map. I have tried setting the zoom level to 1 but this has no effect to the very highly zoomed map.
<script src="http://maps.google.com/maps/api/js?v=3&sensor=false" type="text/javascript"></script>
<script type="text/javascript">
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png",new google.maps.Size(32, 32), new google.maps.Point(0, 0),new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
map.panTo(center);
currentPopup = null;
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
});
addMarker(27.703402,85.311668,'New Road');
center = bounds.getCenter();
map.fitBounds(bounds);
}
</script>
</head>
<body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
<div id="map"></div>
</body>
</html>
How can i decrease the level of zoom for this case?
Your code below is zooming the map to fit the specified bounds:
addMarker(27.703402,85.311668,'New Road');
center = bounds.getCenter();
map.fitBounds(bounds);
If you only have 1 marker and add it to the bounds, that results in the closest zoom possible:
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
}
If you keep track of the number of markers you have "added" to the map (or extended the bounds with), you can only call fitBounds if that number is greater than one. I usually push the markers into an array (for later use) and test the length of that array.
If you will only ever have one marker, don't use fitBounds. Call setCenter, setZoom with the marker position and your desired zoom level.
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
map.setCenter(pt);
map.setZoom(your desired zoom);
}
html,
body,
#map {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
}
<html>
<head>
<script src="http://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" type="text/javascript"></script>
<script type="text/javascript">
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png", new google.maps.Size(32, 32), new google.maps.Point(0, 0), new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
map.setCenter(pt);
map.setZoom(5);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
map.panTo(center);
currentPopup = null;
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
});
addMarker(27.703402, 85.311668, 'New Road');
// center = bounds.getCenter();
// map.fitBounds(bounds);
}
</script>
</head>
<body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
<div id="map"></div>
</body>
</html>
map.setZoom(zoom:number)
https://developers.google.com/maps/documentation/javascript/reference#Map
What you're looking for are the scales for each zoom level. The numbers are in metres. Use these:
20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9 : 2311162.307000
8 : 4622324.614000
7 : 9244649.227000
6 : 18489298.450000
5 : 36978596.910000
4 : 73957193.820000
3 : 147914387.600000
2 : 295828775.300000
1 : 591657550.500000
For zooming in your map two levels, add this small line of code,
map.setZoom(map.getZoom() + 2);
Here is a function I use:
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(52.2, 5),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 7
});
function zoomTo(level) {
google.maps.event.addListener(map, 'zoom_changed', function () {
zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function (event) {
if (this.getZoom() > level && this.initialZoom == true) {
this.setZoom(level);
this.initialZoom = false;
}
google.maps.event.removeListener(zoomChangeBoundsListener);
});
});
}
These methods worked for me, it maybe useful for anyone:
MapOptions interface
set min zoom: mMap.setMinZoomPreference(N);
set max zoom: mMap.setMaxZoomPreference(N);
where N can equal to:
20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9 : 2311162.307000
8 : 4622324.614000
7 : 9244649.227000
6 : 18489298.450000
5 : 36978596.910000
4 : 73957193.820000
3 : 147914387.600000
2 : 295828775.300000
1 : 591657550.500000

Get latitude and longitude of multiple marker (onclick)

I have multiple markers in my map.
How to create a listener to multiple markers and get their latitude and longitude?
When I tried that event listener at one marker, it works. But when I tried that event listener with my multiple marker, it doesnt work.
Here is my code :
var jakarta = new google.maps.LatLng(-6.211544, 106.845172);
var shelterpoint = [];
var shelterName = [];
<?php while ($row = mysql_fetch_array($result)) { ?>
shelterpoint.push(new google.maps.LatLng(<?=$row['Latitude']?>, <?=$row['Longitude']?>));
shelterName.push("<?=$row['Shelter_Name']?>");
<?php } ?>
var markers = [];
var iterator = 0;
var map;
function initialize() {
var mapOptions = {
zoom: 12,
center: jakarta
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
drop();
google.maps.event.addListener(marker, "click", function (event) {
alert(this.position);
});
}
function drop() {
for (var i = 0; i < shelterpoint.length; i++) {
setTimeout(function() {
addMarker();
}, i * 10);
}
}
function addMarker() {
markers.push(new google.maps.Marker({
position: shelterpoint[iterator],
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
title:shelterName[iterator]
}));
iterator++;
}
google.maps.event.addDomListener(window, 'load', initialize);
Please refer the link below.
http://jsfiddle.net/xJ26V/1/
var mapOptions = {
center: new google.maps.LatLng(-33.92, 151.25),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};