Search code examples
javascriptgoogle-earth-plugin

Attaching properties to KmlPlacemark GE Plugin


I have Lat/Lon data coming in as GeoJSON and each point has additional properties associated with it. I need to be able to get these properties passed into the callback function when the KmlPlacemark is clicked. I know I can use closures and individually register event listeners on them but I'd really prefer just having a single listener on the GEWindow object.

My solution involves sticking the properties into the placemark id as JSON data.

var data = {foo: 123, bar: 321};
var placemark = ge.createPlacemark(JSON.stringify(data));

then in the callback it gets parsed back into an object

google.earth.addEventListener(ge.getWindow(), 'click', function(e){
  var target = e.getTarget(),
      data;
  if (target && target.getType() == 'KmlPlacemark'){
    data = JSON.parse(target.getId());
    myHandler(target, data);
  }
});

is there a less hacky way of doing this?


Solution

  • I found a solution I'm happy with. I use an incrementing id for the placemarks and I store the properties in a object using the id as the key.

    Dummy data

    var pointData = [
      {lat: 123, lon: 123, properties: {foo: 1, bar: 2}},
      {lat: 123, lon: 123, properties: {foo: 1, bar: 2}},
      {lat: 123, lon: 123, properties: {foo: 1, bar: 2}}
    ];
    

    Create Placemarks

    var properties = {},
        currentId = 0;
    
    pointData.forEach(function(point){
    
      var id        = (currentId++).toString();
          point     = ge.createPoint(''),
          placemark = ge.createPlacemark(id);
    
      point.setLatitude(point.lat);
      point.setLongitude(point.lon);
      placemark.setGeometry(point);
    
      properties[id] = point.properties;
    });
    

    Lookup properties in event handler

    google.earth.addEventListener(ge.getWindow(), 'click', function(e){
      var target = e.getTarget(),
          data;
      if (target && target.getType() == 'KmlPlacemark'){
        data = properties[target.getId()];
        myHandler(target, data);
      }
    });