125

Is there a way I can add some custom information to my markers for later use. There are ways to have an info-window and a title, but what If I want to associate the marker with other information.

I have other stuff being displayed on the page that depends on the markers so when a marker is click the content on the page has to change depending upon which marker was clicked.I would like store and retrieve the custom data once a marker is lets say clicked etc.

Thanks

Abid
  • 7,149
  • 9
  • 44
  • 51

2 Answers2

230

As a Google Marker is a JavaScript object, you may add custom information in the form key: value, where key is a valid string. They are called object properties and can be approached in many different ways. The value can be anything legal, as simple as numbers or strings, and also functions, or even other objects. Three simple ways: in the declaration, dot notation and square brackets

var markerA = new google.maps.Marker({
    map: map,
    position: new google.maps.LatLng(0, 0),
    customInfo: "Marker A"
});

var markerB = new google.maps.Marker({
    map: map,
    position: new google.maps.LatLng(-10, 0)
});
markerB.customInfo = "Marker B";

var markerC = new google.maps.Marker({
    map: map,
    position: new google.maps.LatLng(-20, 0)
});
markerC['customInfo'] = "Marker C";

Then to retrieve it in a similar manner:

google.maps.event.addListener(markerA, 'click', function() {
    alert(this.customInfo);
});
RPL
  • 3,500
  • 2
  • 21
  • 28
Tina CG Hoehr
  • 6,721
  • 6
  • 44
  • 57
  • 3
    There’s nothing in [the documentation](https://developers.google.com/maps/documentation/javascript/reference#MarkerOptions) formalizing this pattern. Here’s hoping they do rather than break it in a later version. – Adam Apr 17 '13 at 00:46
  • 1
    Property 'customInfo' does not exist on type 'Marker'. – alehn96 Jul 20 '17 at 16:46
  • 2
    If you're using typescript, you may want to use the brackets rather than the dot to assign such properties – Cocoduf Apr 20 '18 at 09:20
  • Using Typescript, there will be an error at line `customInfo: "Marker A"` To prevent this error, you can add in the previous line: // @ts-ignore – Sebastián de Prada Gato Mar 05 '22 at 13:17
14

You can add your own custom properties to the markers (just be careful not to conflict with the API's properties).

geocodezip
  • 158,664
  • 13
  • 220
  • 245