Cedric Arnould
Cedric Arnould

Reputation: 2443

How to convert Position and Zoom Level to LatLngBounds with Google Maps Javascript?

I start to implement a web solution to display a GroundOverlay on a google maps. With IOS and Android, it's possible to add a GroundOverlay, with the center, image and zoom level but it's not possible in Javascript.

So what is the mathematical solution to convert a position (Lat, Lng) to a bound ((Lat,Lng),(Lat,Lng))?

Here is what I have:

Upvotes: 1

Views: 481

Answers (1)

Cedric Arnould
Cedric Arnould

Reputation: 2443

I found a solution mostly inspired from This answer.

function getImageDimensions(imageUrl: string): Observable<{ width: number, height: number }> {
  return new Observable(observer => {
    let image = new Image();
    image.onload = function (event) {
      let loadedImage: any = event.currentTarget;
      observer.next({
        width: loadedImage.width,
        height: loadedImage.height
      });
      observer.complete();
    }
    image.src = imageUrl;
  });
} 



getImageDimensions(imageUrl: string, zoomLevel:number, center: google.maps.LatLng, map: google.maps.Map).subscribe(dimensions => {
  let projection = map.getProjection();
  let zoom = Math.pow(2, zoomLevel) * 2;
  let width = dimensions.width / zoom;
  let height = dimensions.height / zoom;
  let containerPixel = projection.fromLatLngToPoint(center);

  var result = new google.maps.LatLngBounds(
    projection.fromPointToLatLng(
      new google.maps.Point(containerPixel.x - width, containerPixel.y + height)
    ),
    projection.fromPointToLatLng(
      new google.maps.Point(containerPixel.x + width, containerPixel.y - height)
    )
  );
  console.log(result);
});

Upvotes: 1

Related Questions