Search code examples
javascriptgoogle-mapspolyline

How to draw a circle and line on Google Map pixel-based?


Is it possible to draw circles and polylines on Google maps based on pixel dimensions? Allow me to explain...

I have a marker on a map. Next, I want to draw a circle around it, with the marker being the exact center. I'd like the circle to have a fixed pixel-based radius. However, as the Google Maps API takes distance in meters to base the radius on, the size of the circle varies based on the zoom level, which is what I do not want.

Another example is an angled Polyline. I'm drawing such a line from the marker into a certain direction. Again the distance is based on meters, not pixels, thus the zoom shrinks or grows the size of the line. Another unwanted side effect is that due the sperical projection of the map (if I understand this correctly), a line angled at 90 degrees, will not draw it precisely at east.

What I'm looking for is the convenience of these drawing objects on the map, without tying them to map dimensions, just to hard pixels. Is such a thing possible, or does it mean I need to start from scratch with a custom div and some kind of SVG library?


Solution

  • It's easier than you might think, use Symbols.

    For a circle there is a predefined path:

    new google.maps.Marker({
        position: centerLatLngOfTheCircle,
        icon: {
            path: google.maps.SymbolPath.CIRCLE,
            scale: yourDesiredRadius,
            strokeWeight: 1,
        },
        map: map
    });
    

    For a polyline you must assign a custom path:

    line = new google.maps.Marker({
        position: startLatLngOfTheLine,
        icon: {
            path: ['M0 0 ', 
                   (Math.cos(Math.PI * angle / 180)), 
                   (Math.sin(Math.PI * angle / 180))].join(' '),
            scale: desiredStrokeLength,
            strokeWeight: 1
        },
        map: map
    });
    

    (the angle is counted clockwise, starting at 3:00)

    Demo: http://jsfiddle.net/doktormolle/y8S8e/