Handle different google maps center depending on media query

只愿长相守 提交于 2019-12-24 12:46:52

问题


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

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:


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/



来源:https://stackoverflow.com/questions/33380499/handle-different-google-maps-center-depending-on-media-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!