Google maps function from LatLngToContainerPixel (LatLng) not working

I'm trying to get the pixel coordinates of the market using the fromLatLngToContainerPixel (LatLng) function. I wasn't sure how to use it, but after searching for some examples on SO, I think I got it. The problem is that the function always returns "unifined".

Google maps api ref: https://developers.google.com/maps/documentation/javascript/reference?csw=1#MapCanvasProjection

Please, help.

code:

var map, overlay;

function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882, 131.044922);
map = new google.maps.Map(document.getElementById('gMap'), {
    zoom : 13,
    center : myLatlng,
    disableDefaultUI: true,
    draggable: false,
    scrollwheel: false,
    disableDoubleClickZoom: true
});

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

var marker = new google.maps.Marker({
    position: myLatlng, 
    optimized: false, 
    map:map
});

 var projection = overlay.getProjection(); 
        var pixel =     projection.fromLatLngToContainerPixel(marker.getPosition());
        console.log(pixel);
}
google.maps.event.addDomListener(window, 'load', initialize);

      

+3


source to share


1 answer


From the documentation :

getProjection()

: Returns the MapCanvasProjection associated with this OverlayView. The projection is not initialized until the API calls onAdd.

onAdd()

... Implement this method to initialize overlay DOM elements. This method is called once after calling setMap () with a valid map. At this point, the panels and projection will be initialized.



So the solution is to implement the method onAdd()

and access the projection inside onAdd()

:

function initialize() {
  var myLatlng = new google.maps.LatLng(-25.363882, 131.044922);
  map = new google.maps.Map(document.getElementById('gMap'), {
    zoom: 13,
    center: myLatlng,
    disableDefaultUI: true,
    draggable: false,
    scrollwheel: false,
    disableDoubleClickZoom: true
  });

  var marker = new google.maps.Marker({
    position: myLatlng,
    optimized: false,
    map: map
  });

  var overlay = new google.maps.OverlayView();
  overlay.draw = function() {};
  overlay.onAdd = function() {
    var projection = this.getProjection();
    var pixel = projection.fromLatLngToContainerPixel(marker.getPosition());
    console.log(pixel);
  };
  overlay.setMap(map);
}

      

+4


source







All Articles