Home » Javascript » Marker ID in Google Map

Marker ID in Google Map

How to get Marker ID in Google Map when we click on it

Google Map Marker ID
Here I am going to show an example for adding IDs to the markers on the Google Map and getting/alerting the ID of the clicked marker.

HTML For showing Google Map Markers

<!DOCTYPE html>
<meta charset="utf-8">
<title>Google Map</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<style type="text/css">
.google-map {
width: 60%;
height: 500px;
margin: 0 auto;
border: 1px solid #c5c5c5;
<div class="google-map" id="map-canvas"></div>

Here, we are loading the map inside id=”map-canvas” div. In order to load Google map, we have to add Google map API url in the head tag of the HTML page.

Javascript For Google Map

<!--Script for google map-->
<script type="text/javascript">
function initialize_list() {
var latlng = new google.maps.LatLng(33.22949814144931,-99.82177934375);
var myOptions = {
zoom: 5,
center: latlng

var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);

var hotels = [
['Hotel 1, Place Name1, City1, State1', 33.22949814144931,-99.82177934375, 4, 1],
['Hotel 2, Place Name2, City2, State2', 33.376412351246586,-96.78955278125, 3, 2],
['Hotel 3, Place Name3, City3, State3', 35.08395557927625,-93.84521684375, 2, 3],
['Hotel 4, Place Name4, City4, State4', 37.631634755806274,-105.31494340625, 1, 4]

for (var i = 0; i < hotels.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(hotels[i][1], hotels[i][2]),
map: map,
id: hotels[i][4], //we are adding IDs to the marker here
title: hotels[i][0]

google.maps.event.addListener(marker, "click", function() {
var marker = this;
alert('ID is :'+ this.id);

window.onload = initialize_list;

Here using ‘id’ we are assigning ID value to the marked. And on the click event or when we click on the marker, we will alert the clicked markers ID.

Demo for getting Google Map Marker ID

Responsive Video Background

Leave a Reply

Your email address will not be published. Required fields are marked *