Duncan's blog

December 18, 2013

Google Maps API – polyline labels

Filed under: Google Maps,Javascript — duncan @ 6:40 pm
Tags:

Someone recently asked a question on StackOverflow about how to add labels to a polyline in response to user clicks on the line, displaying the coordinates.  I had previously posted an article here where I displayed labels on multiple polylines showing their distance.  I simplified that code to provide a solution to the question, and thought it worth posting as a new blog article.

Again all the tricky label code is from an article by Marc Ridey.  I won’t re-post that to this article, just the contents of the initialize function that ties the labels together with the polyline.

function initialize() {
    var stavanger=new google.maps.LatLng(58.983991,5.734863);
    var amsterdam=new google.maps.LatLng(52.395715,4.888916);
    var london=new google.maps.LatLng(51.508742,-0.120850);

    var map = new google.maps.Map(document.getElementById("map_canvas"), {
        zoom: 5,
        center: amsterdam,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var flightPath=new google.maps.Polyline({
        path:[stavanger,amsterdam,london],
        strokeColor:"#0000FF",
        strokeOpacity:0.8,
        strokeWeight:2,
        map:map
    });

    // create an invisible marker
    labelMarker = new google.maps.Marker({
        position: stavanger,  
        map: map,
        visible: false
    });

    var myLabel = new Label();

    // lets add an event listener, if you click the line, i'll tell you the coordinates you clicked
    google.maps.event.addListener(flightPath, 'click', function(e) {
        labelMarker.setPosition(e.latLng)
        myLabel.bindTo('position', labelMarker, 'position');
        myLabel.set('text', e.latLng.toString());
        myLabel.setMap(map);
    });
}

And you end up with something like:

polylines

One issue with this code is that the label obscures part of the line, so you can’t always click anywhere on the line, only those spaces that don’t have the label over them.

Advertisements

1 Comment »

  1. Great article, i was looking for this except one thing, how can i achieve the same thing using Static API within the URL?

    Comment by guzelonur — May 10, 2015 @ 10:17 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: