Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use fromPointToLatLng on google maps v3

This is my code:

var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map,'projection_changed', function () {
    var proj = map.getProjection();
    ltBound = proj.fromPointToLatLng(new google.maps.Point(0,100))
    rbBound = proj.fromPointToLatLng(new google.maps.Point(100,200))
    console.log(ltBound,rbBound)
});

I want to make a node on Google Maps, but I can't use the fromPointToLatLng on right way. What can I do?

like image 987
zjm1126 Avatar asked Dec 13 '22 19:12

zjm1126


2 Answers

Here's how I use the method fromPointToLatLng(). You first need to find the Lat / Lng of the top left point on the map then calculate an offset from there.

var pixelToLatlng = function(xcoor, ycoor) {
  var ne = map.getBounds().getNorthEast();
  var sw = map.getBounds().getSouthWest();
  var projection = map.getProjection();
  var topRight = projection.fromLatLngToPoint(ne);
  var bottomLeft = projection.fromLatLngToPoint(sw);
  var scale = 1 << map.getZoom();
  var newLatlng = projection.fromPointToLatLng(new google.maps.Point(xcoor / scale + bottomLeft.x, ycoor / scale + topRight.y));
  return newLatlng;
};

Try out the fiddle here: http://jsfiddle.net/mhaq865o/5/

You can either use the fromPointToLatLng() method or OverlayView method as described here http://magicalrosebud.com/how-to-use-googlemaps-api-frompointtolatlng/

like image 140
Byron Singh Avatar answered Jan 02 '23 07:01

Byron Singh


The fromPointToLatLng and fromLatLngToPoint methods in Projection translate between points in a 256x256 coordinate system and real world coordinates.

The entire Google Map is 256x256 pixels when you are at zoom level 0. Try zooming out and outputting the point you get when you click around the map:

google.maps.event.addListener(map, 'click', function(event) {
    var proj = map.getProjection();
    console.log('latLng: ' + event.latLng);
    console.log('Point:  ' + proj.fromLatLngToPoint(event.latLng));
});

I think you only need to know/use this if you want to compute a zoom level or do something similar where you need to know the relationship between real world coordinates and on-screen pixels.

You ask about adding a "node" to the map. If you're thinking of what the documentation calls "markers", then see their section on markers.

like image 31
Martin Geisler Avatar answered Jan 02 '23 06:01

Martin Geisler