Skip to content

Vertical calculation differs from google maps #30

Description

@jantimon

I am trying to calculate the coords of the (north east and south west) edges of a map with a given height and width:

https://jsfiddle.net/0umus671/

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="https://unpkg.com/sphericalmercator@1.0.5"></script>
<div id="map_canvas"></div>
<script>
  var mapEl = document.getElementById('map_canvas');
  var map;
  var mapHeight = 200;
  var mapWidth = 500;
  var mapZoom = 10;
  var mapCenter = [47.376887, 8.541694];

  mapEl.style.width = mapWidth + 'px';
  mapEl.style.height = mapHeight + 'px';


  var sphericalmercator = new SphericalMercator();
  var ll0 = sphericalmercator.ll([0, 0], mapZoom);
  var ll1 = sphericalmercator.ll([mapWidth, mapHeight], mapZoom);
  var latDelta = Math.abs(ll0[1] - ll1[1]);
  var lngDelta = Math.abs(ll0[0] - ll1[0]);

  var south = mapCenter[0] - latDelta / 2
  var north = mapCenter[0] + latDelta / 2
  var west = mapCenter[1] - lngDelta / 2
  var east = mapCenter[1] + lngDelta / 2;
  
  var northWestMarker = [north, west];
  var southEastMarker = [south, east];

  function initialize() {
    var mapOptions = {
      zoom: mapZoom,
      center: new google.maps.LatLng(mapCenter[0], mapCenter[1]),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map_canvas'),
      mapOptions);
    new google.maps.Marker({
      map: map,
      position: new google.maps.LatLng(northWestMarker[0], northWestMarker[1])
    });
    new google.maps.Marker({
      map: map,
      position: new google.maps.LatLng(southEastMarker[0], southEastMarker[1])
    })
    setTimeout(() => {
     
     // Should return the same result:
     console.log(map.getBounds().toJSON())
     console.log({south, west, north, east})

    }, 500)
  }

  google.maps.event.addDomListener(window, 'load', initialize);
  

</script>

Unfortunately the latitude calculation is wrong and the elements are not in the north/south corners:

google_maps__recenter_a_map_-_jsfiddle

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions