Search code examples
javascriptgoogle-mapsgoogle-maps-api-3google-maps-markers

Interact with Google's My Maps


I created an own map with Google's My Maps. I made a new layer and placed some markers on it.
Is it possible to interact with those markers?

What I want to do "iterating" over those markers in chronological order.
Consider the following map: Remote Islands of the World.
I would make a button "Next" on my website. Whenever the user clicks the button, the maps jumps from "Bouvet Island" to "St Helena", after another click it jumps to "Izu Islands - Miyakejima" etc.

I don't even know if it's possible or where to find more information about how to achieve it.


Solution

  • One option would be to create a Google Maps Javascript API v3 map and access the KML data from MyMaps using a third party KML parser (like geoxml3) through a proxy.

    example (displays the KML point names in the sidebar using geoxml3, but could be modified to add a "next" button that sequences through them).

    example with "next"/"previous" links in infowindow and next button above the map

    Added this code inside the useTheData function (and equivalents for polygons and polylines):

    if (placemark.marker) {
      google.maps.event.addListener(placemark.marker, 'click', function(i) {
    
        return function(evt) {
        // add next and previous links to infowindow when the placemark is clicked
        infowindow.setContent(infowindow.getContent()+"<br><a href='javascript:next("+i+");'>next</a>&nbsp;-&nbsp;<a href='javascript:prev("+i+");'>previous</a>");
        // track the last opened placemark 
        openInfoWindow = i;
      }}(i));
    

    Then these functions to open the next infowindow:

    function next(i) {
      var next = (i+1) % geoXmlDoc.placemarks.length;
      if (geoXmlDoc.placemarks[next].marker) {
       google.maps.event.trigger(geoXmlDoc.placemarks[next].marker, "click");
      } else if (geoXmlDoc.placemarks[next].polyline) {
       google.maps.event.trigger(geoXmlDoc.placemarks[next].polyline, "click");
      } else if (geoXmlDoc.placemarks[next].polygon) {
       google.maps.event.trigger(geoXmlDoc.placemarks[next].polygon, "click");
      }
    }
    function nextBtn() {
      // handle case where button is clicked before any placemarks on the map
      if (!openInfoWindow) openInfoWindow = 0;
      next(openInfoWindow);     
    }
    

    Note that because geoxml3 uses XmlHttpRequest to access the data, a proxy must be used on the domain displaying the page to overcome the same domain restriction on XmlHttpRequest.