Getting from Google Earth KML to Google Maps Javascript markup

It irks me to no end you have to have the Pro version of Google Earth to import Shapefiles. This is useful if you want to turn shapefiles into KML and pass them around, use them as an overlay on a plain vanilla Google map, etc. But why can’t I just save out marker points and polygons into the Google Maps javascript markup?

This PHP script helps with converting kml POLYGONS to google maps polygons. It needs some tweeking to adapt to PLACEMARKS, which I’m more interested in.

Script source from the google-maps-api Google Group originally seen here:

<?php

$kmlfile = 'http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&output=kml&msid=109250181535574469723.00043cb961e5234cea628';

$xml = simplexml_load_file($kmlfile) or die("url not loading");

echo "var states = { <br/>";
foreach($xml->Document->Placemark as $placemark) {
  $name = $placemark->name;
  echo "'" . $name . "' : [";
  $coords = $placemark->Polygon->outerBoundaryIs->LinearRing->coordinates;
  $coordsArray = split("\n", $coords);
  for ($i = 0; $i < count($coordsArray); $i++) {
    $latlngArray = split(",", $coordsArray[$i]);
      if (count($latlngArray) == 3) {
      $lat = $latlngArray[1];
      $lng = $latlngArray[0];
      echo "new GLatLng(" . $lat . "," . $lng . ")";
      if ($i != count($coordsArray) -2) echo ", ";
    }
  }
  echo "],<br/>";
}
echo "}";
?>

Sample results here which are used by this HTML page to draw the polygons using this function (below):

function initialize() {
   if (GBrowserIsCompatible()) {
     map = new GMap2(document.getElementById("map_canvas"), {draggableCursor: 'crosshair'});
     map.setCenter(new GLatLng(42, -99), 3);
     map.addControl(new GSmallMapControl());
     for (stateCode in stateBorders) {
       var polygon = createPoly(stateCode);
       map.addOverlay(polygon);
     }
  }
}

So still not there, but closer.

One Response to “Getting from Google Earth KML to Google Maps Javascript markup”

  1. [...] Check it out! While looking through the blogosphere we stumbled on an interesting post today.Here’s a quick excerptThis is useful if you want to turn shapefiles into KML and pass them around, use them as an overlay on a plain vanilla Google map, etc. But why can’tI just save out marker points and polygons into the Google Maps javascript markup? … [...]