Make KML and markerclusterer work togeter locally

Share on TumblrSave on Delicious

KML (Keyhole markup language) is an XML notation for expressing geographic annotation and visualization within Internet-based, two-dimensional maps and three-dimensional Earth browsers. With KML, the developer could expose quite a lot of geographical information on the map. The following snapshot shows and example of displaying 7000 points on google maps through KML.  You can also view the example from the link. The code is very simple and straightforward. We just nee to introduce a KmlLayer to the map, the code is as follows:

var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
var nwsLayer = new google.maps.KmlLayer("http://demos.prowebx.net/kmz/events-list.kml");
nwsLayer.setMap(map);

The issue is that there are too many markers on the map and the user. As we know there is a third party library named MarkerClusterer which can help us to cluster neighboring markers together. But in the above implementation, the KML is sent to the google server and google helps us to generate the markers for us. We don’t have directly access to the markers on the map.

There is another library which can help us to parse the KML locally and let us have the direct access to the markers named geoxml3. So we can use geoxml3 library and markerclusterer together to parse the KML locally and cluster the markers on the map.

The implementation is easy as well, firstly you will need to import two libraries:

<script type="text/javascript" charset="utf-8" src="script/geoxml3.js"></script>
<script type="text/javascript" charset="utf-8" src="script/markerclusterer.js"></script>
//Draw the map in the map-canvas div
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
//The markercluster's options
var mcOptions = {gridSize: 50, maxZoom: 15};
//Construct an empty markerclusterer object
markerclusterer  = new MarkerClusterer(map, [], mcOptions);
//Construct a geoXML3 parser
var myParser = new geoXML3.parser({
		map: map, singleInfoWindow:true,
		createMarker:function(placemark){
                        //Constructing marker for each Placemark node, and then add it to the markclustere
		        var point = new google.maps.LatLng(placemark.point.lat, placemark.point.lng);
		        var marker = new google.maps.Marker({position:point});
		        markerclusterer.addMarker(marker);
		}
	});
        myParser.parse('events-list.kml')

Then the KML file is parsed locally and the markers in the KML file are clustered by the markerclusterer. You can view the demo here.

No related posts.

Comments are closed.