massic80
massic80

Reputation: 319

How to get two Google Maps Markers at a fixed pixel distance

I've been struggling for hours looking for the solution to my question: I need to place two markers around the center of the map, allowing enough space for not having any overlay between them, regardless to zoom or map position (since latitude isn't linear with vertical position). I know that the Projections can help me, but I can't get how to use them. How shall I do?

Upvotes: -3

Views: 47

Answers (1)

massic80
massic80

Reputation: 319

In a nutshell, this is the solution:

/** Returns the LatLng position at a pixel {@link distance} from {@link position} at the current zoom.
* @param {google.maps.LatLng} position the position to start from
* @param {{ x: number; y: number; }} distance the distance coordinates from {@link position} to calculate the location in. {@link distance}.x increases going to the right, {@link distance}.y increases going down. 
*/
const getFixedPixelDistanceLocationFrom = (position: google.maps.LatLng, distance: { x: number; y: number; }) => {
    const zoomScale = Math.pow(2, this.map!.getZoom()!),
        projection = this.map!.getProjection()!,
        centerPixel = projection.fromLatLngToPoint(position)!;
    // The distance is intended at current zoom, hence the projection must be magnified accordingly
    return projection.fromPointToLatLng(
        new google.maps.Point(
            ((centerPixel.x * zoomScale) + distance.x) / zoomScale,
            ((centerPixel.y * zoomScale) + distance.y) / zoomScale
        )
    )!;
};

This method allows you to get a fixed-pixel-distance LatLng point from a given one. Demo: https://jsfiddle.net/massic80/6nsq7yo3/

Check Google Docs about projection

Upvotes: -1

Related Questions