Google Map- Set Markers and Open InfoWindow for Each Marker

Set Markers and Open InfoWindow for Each Marker

Run a function when the user clicks on the map.

The placeMarker() function places a marker where the user has clicked, and shows an infowindow with the latitudes and longitudes of the marker:


<!DOCTYPE html>
<html>
<head>
<script
src="http://maps.googleapis.com/maps/api/js">
</script>

<script>
var map;
var myCenter=new google.maps.LatLng(51.508742,-0.120850);

function initialize()
{
var mapProp = {
center:myCenter,
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};

map = new google.maps.Map(document.getElementById("googleMap"),mapProp);

google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}

function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() + '<br>Longitude: ' + location.lng()
});
infowindow.open(map,marker);
}

google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>

<body>
<div id="googleMap" style="width:500px;height:380px;"></div>

</body>
</html>

Output : 

 




Pankaj Singh Sugara

Author Pankaj Singh Sugara

Experienced Software Engineer with a demonstrated history of working in the marketing and advertising industry. Skilled in SQL, Web Applications, PHP, WordPress, and Joomla. Strong engineering professional with a B-TECH focused in Information Technology from JCDM College of Engineering Sirsa, Haryana.

More posts by Pankaj Singh Sugara