Displaying muiple points on a google map using my Umbraco datatype

A while back I wrote about displaying maps on your Umbraco website using my Google maps datatype for Umbraco. Since then I've had a number of requests to provide an example of how to display multiple points on a map and Matt Perry and I have finally come up with such an example.

The first step is to write a simple XSLT macro that will list out all of the points that you want to show. I'm not going to give that example here, but the output should look similar to the following:


<h1>Service stations in Lancashire</h1>
<p>The following data is a list of latitude and longtitude points and a description for service stations in Lancashire</p>
<div id="map"></div>
<!-- Rendered from a simply XSLT Extension -->
<div class="point">52.94341429133642,-2.1892619132995605,17,A34-STONE ROAD TITTENSOR N/B</div>
<div class="point">53.029535856006525,-2.176837921142578,16,A50-POTTERIES WAY</div>

Note: The empty map div is a placeholder for the Google map itself.

Quite a few people have written to me asking how one would add several points to a single instance of my datatype and the short answer is you can't. You'll need to create an Umbraco node for every point you want to display on your map, each node containing an instance of my datatype.

In order to render the map you'll need some javascript similar to the following:


var m= new GMap2(document.getElementById('map'));
m.setCenter(new GLatLng(0, 0), 0);
var bounds = new GLatLngBounds();

m.addControl(new GLargeMapControl());
m.addControl(new GMapTypeControl());

var arrayList = $(".point");  // set of elements with class 'point'

$.each(arrayList, function() {
    var value = $(this).html();
    value = $.trim(value);

    var point = value.split(',');
    var lat = parseFloat(point[0]);
    var lon = parseFloat(point[1]);
    var desc = point[3];

    var point = new GLatLng(lat, lon);
    bounds.extend(point);    

    m.addOverlay(createMarker(point,desc));
});

// Creates a marker at the given point
// Clicking the marker will hide it

function createMarker(latlng,desc) {

    var marker = new GMarker(latlng);
    marker.name = desc;
    
    GEvent.addListener(marker,"click", function() {
        var myHtml =  desc;
        m.openInfoWindowHtml(latlng, myHtml);
    });

    return marker;
}

m.setZoom(m.getBoundsZoomLevel(bounds));
m.setCenter(bounds.getCenter());

For the above to work, you'll need to include jQuery and the Google Maps javascript API in your page. The resulting map should zoom and centre according to the points that you have added.

Accessibility alert: Please provide a header and description paragraph before your map point data as I have in my example in order to ensure that the data makes sense with javascript disabled or to screen readers.

Comments

Leave a comment