Question

I found this great tutorial for extending GMarkers in v2 google maps: http://www.googlemapsbook.com/2007/01/22/extending-gmarker/

Unfortunately, in v3 the set-up of a marker is very different (eg you have to pass in the map it will be added to as a parameter, so can't have a standalone google.maps.Marker object to act as a prototype, or at least not until after your map has initialised).

Does anyone know how to extend a google maps v3 marker?

*edit - turns out I was wrong about the map being a required parameter. I'll post my v3 extension as an answer later and mark this as a community question

Was it helpful?

Solution

Below is what I eventually used (I've stripped out a lot of code that I used for my custom marker to leave just the bare bones so I may have made a mistake in the editing). newObj() is a function (based on Douglas Crockford's code) for generating a new object from a prototype, rather than using a constructor function.

function newObj(o) {
    var params = Array.prototype.slice.call(arguments,1);
    function F() {}
    F.prototype = o;
    var obj = new F();
    if(params.length) {
        obj.init.apply(obj,params);
    }
    return obj;
}

var MyMarkerProto = function() {
    var proto  = new google.maps.Marker(new google.maps.LatLng(0, 0));

    proto.init = function (data) {
        this.setPosition(new google.maps.LatLng(parseFloat(data.lat), parseFloat(data.lng)));
    }
    return proto;

}();

var myMarker = newObj(MyMarkerProto, {
    lat: 51,
    lng: 48,
    otherData: "some other value"
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top