How to convert LatLng to (x, y) pixels and vice versa?

I am using the Google Maps API V3 and I want to create an editable rectangle 100px X 100px when the user clicks on the map.

Now I only need to (x, y) specify what the user clicks, and then lat and lng (x + 100, y + 100). Any ideas?

+5
source share
2 answers

This function should create a 100 x100 rectangle around the center (LatLng) that you pass to it.

function setRectangle(center){
    var scale = Math.pow(2,map.getZoom());
    var proj = map.getProjection();
    var wc = proj.fromLatLngToPoint(center);
    var bounds = new google.maps.LatLngBounds();
    var sw = new google.maps.Point(((wc.x * scale) - 50)/ scale, ((wc.y * scale) - 50)/ scale);
    bounds.extend(proj.fromPointToLatLng(sw));
    var ne = new google.maps.Point(((wc.x * scale) + 50)/ scale, ((wc.y * scale) + 50)/ scale);
    bounds.extend(proj.fromPointToLatLng(ne));
    var opts = {
        bounds: bounds,
        map: map,
        editable:true
    }
    var rect = new google.maps.Rectangle(opts);

}
+15
source

you can use

var overlay = new google.maps.OverlayView();
overlay.draw = function() {};
overlay.setMap(map);

var proj = overlay.getProjection();
var pos = marker.getPosition();
var p = proj.fromLatLngToContainerPixel(pos);

now you can get pixels from px and py

+7
source

All Articles