如何在Google Maps点击事件中创建存储经纬度的Cookie?
没问题!我帮你在现有代码基础上添加Cookie存储经纬度的功能,下面分步骤说明并给出完整代码:
1. 添加Cookie操作工具函数
首先我们需要几个简单的工具函数来处理Cookie的读写——原生JS没有直接的Cookie操作API,自己封装一下会更方便:
// 设置Cookie,可指定过期天数(默认7天) function setCookie(name, value, days = 7) { const date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); const expires = "expires=" + date.toUTCString(); document.cookie = `${name}=${value}; ${expires}; path=/`; } // 获取指定名称的Cookie值 function getCookie(name) { const nameEQ = `${name}=`; const ca = document.cookie.split(';'); for(let i=0;i < ca.length;i++) { let c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; }
2. 修改现有代码,添加Cookie存储逻辑
接下来我们对你的原有代码做两处核心改动:
- 点击地图标记位置时,自动将经纬度存入Cookie
- 页面加载初始化时,读取Cookie中的经纬度(如果存在),自动恢复标记、填充输入框和地址
完整修改后的代码
var map; var geocoder; var marker; // 把marker变量提升到全局,方便初始化时访问 // Cookie操作工具函数 function setCookie(name, value, days = 7) { const date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); const expires = "expires=" + date.toUTCString(); document.cookie = `${name}=${value}; ${expires}; path=/`; } function getCookie(name) { const nameEQ = `${name}=`; const ca = document.cookie.split(';'); for(let i=0;i < ca.length;i++) { let c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function initialize() { var myOptions = { center: new google.maps.LatLng(38.89103282648849, -97.646484375), zoom: 4, mapTypeId: google.maps.MapTypeId.ROADMAP }; geocoder = new google.maps.Geocoder(); map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); // 页面加载时检查Cookie,恢复之前存储的经纬度 const savedLat = getCookie('mapLat'); const savedLng = getCookie('mapLng'); if (savedLat && savedLng) { const savedLocation = new google.maps.LatLng(parseFloat(savedLat), parseFloat(savedLng)); placeMarker(savedLocation); getAddress(savedLocation); // 把地图中心移动到保存的位置,同时放大缩放级别 map.setCenter(savedLocation); map.setZoom(10); } google.maps.event.addListener(map, 'click', function(event) { placeMarker(event.latLng); }); } function placeMarker(location) { if(marker){ marker.setPosition(location); }else{ marker = new google.maps.Marker({ position: location, map: map }); } const lat = location.lat(); const lng = location.lng(); document.getElementById('lat').value = lat; document.getElementById('lng').value = lng; // 将经纬度存入Cookie,有效期7天(可根据需求调整天数) setCookie('mapLat', lat, 7); setCookie('mapLng', lng, 7); getAddress(location); } function getAddress(latLng) { geocoder.geocode( {'latLng': latLng}, function(results, status) { if(status === google.maps.GeocoderStatus.OK) { // 修复原代码的赋值错误,改为严格相等判断 if(results[0]) { document.getElementById("address").value = results[0].formatted_address; } else { document.getElementById("address").value = "No results"; } } else { document.getElementById("address").value = status; } }); } google.maps.event.addDomListener(window, 'load', initialize);
3. 关键改动说明
- 把
marker变量提升到全局作用域,确保初始化时可以直接修改标记位置 - 新增
setCookie和getCookie工具函数,支持自定义Cookie有效期 - 在
placeMarker函数中添加了存储经纬度到Cookie的逻辑 - 在
initialize函数中添加了读取Cookie、恢复标记/输入框/地图中心的逻辑 - 修复了原代码中
if(status = google.maps.GeocoderStatus.OK)的赋值错误,改为严格相等===
这样用户下次打开页面时,之前点击选择的经纬度会自动恢复,地址输入框也会自动填充对应的地址啦!
内容的提问来源于stack exchange,提问作者Theopap
相关产品推荐
相关产品推荐

