Ali Behzadian Nejad
Ali Behzadian Nejad

Reputation: 9044

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

I am using google maps API V3 and I want to create an editable 100px X 100px Rectangle when user clicks on the map.

Now I only need to have (x,y) point that user clicks and then lat and lng of (x+100 , y+100). Any Idea?

Upvotes: 5

Views: 12841

Answers (2)

Marcelo
Marcelo

Reputation: 9407

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);

}

Upvotes: 16

Ramesh Kotha
Ramesh Kotha

Reputation: 8322

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 p.x and p.y

Upvotes: 7

Related Questions