Handle different google maps center depending on m

2019-08-14 17:45发布

This is probably really simple to do, I am just not sure how to handle it currently. I am building a site using Foundation 5 as responsive framework and in the footer section there's a map. In the tablet and desktop versions the contact form is positioned over the map with the map visible on both sides of the form element. The mobile version has the map first and the contact form afterwards. To put it graphically it's something like that.

Tablet/Desktop Version

Tablet/Desktop Version

Mobile Version

Mobile Version

So, now, in terms of responsiveness what I would normally do to keep the map centered is use:

google.maps.event.addDomListener(window, 'resize', function() {
    map.setCenter(new google.maps.LatLng(lat,lng));
});

Now that would work OK if the map's center was actually the map's center, but as you can see in the examples, the map center in the Tablet/Desktop version is a little to the East of the Marker and in the Mobile Version the Center and the Marker share position.

Is there any way to use the resize event listener with different coordinates depending on media query or window size?

1条回答
▲ chillily
2楼-- · 2019-08-14 18:05

Use matchMedia to determine each case:

google.maps.event.addDomListener(window, 'resize', function() {
  var latLng;
  if (window.matchMedia("(min-width: 400px)").matches) {
    latLng = new google.maps.LatLng(bigLat,bigLng);
  } else {
    latLng = new google.maps.LatLng(smallLat,smallLng);
  }
  map.setCenter(latLng);
});

See https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia

Also, resize is one of those events that can fire VERY rapidly. You may want to consider throttling that event: http://ejohn.org/blog/learning-from-twitter/

查看更多
登录 后发表回答