Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 965
Ali Behzadian Nejad Avatar asked Aug 09 '12 09:08

Ali Behzadian Nejad


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

}
like image 183
Marcelo Avatar answered Oct 24 '22 10:10

Marcelo


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

like image 35
Ramesh Kotha Avatar answered Oct 24 '22 09:10

Ramesh Kotha