Search code examples
javascriptgoogle-mapskml

How to Get Clicked KML point coordination in Javascript


I want to get clicked point's coordinates. However I get "undefined" string.

The code is below

    kmlLayer.addListener("click", (kmlEvent) => {
        const text = kmlEvent.featureData.coordinates;
        window.alert(text);
    });

And my .kml file sample:


<Placemark>
        <name>AYRANCI MAHALLESİ</name>
        <description>DİKMEN CAD. UÇARLI SOKAK CEMAL SÜREYA PARKI 2 ADET GERİ DÖNÜŞÜM KUMBARASI</description>
        <styleUrl>#icon-165</styleUrl>
        <Point>
          <coordinates>
            32.8466184,39.9044488,0
          </coordinates>
        </Point>
</Placemark>

I can get the description of placemark but could not get the coordinates.


Solution

  • The coordinates of the clicked feature are at the KmlEvent level, not in the featureData information:

    google.maps.KmlMouseEvent interface

    The properties of a click event on a KML/KMZ or GeoRSS document.

    Properties
    ...
    latLng
    Type: LatLng
    The position at which to anchor an infowindow on the clicked feature.
    ...

    proof of concept fiddle

    screenshot of infowindow displaying the feature's coordinates

    code snippet:

    function initMap() {
      const map = new google.maps.Map(document.getElementById("map"), {
        zoom: 11,
        center: {
          lat: 41.876,
          lng: -87.624
        },
      });
      const kmlLayer = new google.maps.KmlLayer({
        url: "http://www.geocodezip.com/geoxml3_test/kml/SO_20210403_Placemark.kml",
        map: map,
        suppressInfoWindows: true
      });
      const infowindow = new google.maps.InfoWindow();
      kmlLayer.addListener("click", (kmlEvent) => {
        const text = kmlEvent.latLng.toUrlValue(6);
        const description = kmlEvent.featureData.description;
        const name = kmlEvent.featureData.name;
        infowindow.setContent("<b>" + name + "</b><br>" + description + "<br>" + text);
        infowindow.setPosition(kmlEvent.latLng)
        infowindow.open(map);
      });
    }
    /* Always set the map height explicitly to define the size of the div
           * element that contains the map. */
    #map {
      height: 100%;
    }
    
    /* Optional: Makes the sample page fill the window. */
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <!DOCTYPE html>
    <html>
    
      <head>
        <title>KML Layers</title>
        <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
        <!-- jsFiddle will insert css and js -->
      </head>
    
      <body>
        <div id="map"></div>
    
        <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
        <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly" async></script>
      </body>
    
    </html>