【问题标题】:Keep zoom when refreshing webpage刷新网页时保持缩放
【发布时间】:2015-03-16 19:34:17
【问题描述】:

大家晚上好。现在我正在开发一个 gps 本地化网络服务器,我正在从 GPS 卡获取坐标到服务器中的端口嗅探器,它将坐标写入 SQL 数据库。 我遇到的问题是我不断刷新网页以获取新数据,但如果用户放大或缩小,或在刷新时移动中心,所有这些更改都会丢失。

这是 JS 片段:

    <script>
// functions below
//Make an array with the coordinates from the db
function initialize() {
    var posicion= [];
    for (var i=0; i< lat.length; i++){
    posicion.push(new google.maps.LatLng(lat[i], long[i])); // Add the coordinates
    }

  var mapOptions = {
    zoom: 16,
     center: posicion[lat.length-1],
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };
 var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); // Render our map within the empty div

  var linea = new google.maps.Polyline({
  path: posicion,
    geodesic: true,
    strokeColor: '#FF0000',
    strokeOpacity: 1.0,
    strokeWeight: 2
  });

  linea.setMap(map);
}

google.maps.event.addDomListener(window, 'load', initialize);  
</script>

【问题讨论】:

  • 我可能会使用hash in the url。在用户缩放时设置它,并在页面加载时读取它(如果它在那里)
  • 我认为你应该尝试使用ajax之类的东西,而不是刷新整个页面。

标签: javascript php google-maps gps


【解决方案1】:

您必须监听事件“bounds_changed”,然后将结果保存在 cookie 中。当您重新加载时,您将这些值用作缩放和居中的默认值

google.maps.event.addListener(map, 'bounds_changed', (function () {
  var centerTobeSavedOnCookie = map.getCenter();
  var zoomTobeSavedOnCookie = map.getZoom();
  // save values to cookies
  setCookie("gmapDefaultZoom", zoomTobeSavedOnCookie, 1);
  setCookie("gmapDefaultCenter", centerTobeSavedOnCookie , 1);
}()));

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}

【讨论】:

  • 我正在尝试使用您的解决方案,但我确定我使用错误的 cookie :(
猜你喜欢
  • 1970-01-01
  • 2023-02-08
  • 2022-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
  • 2018-07-25
  • 2017-12-14
相关资源
最近更新 更多