JavaScript如何在Google地图代码中插入cookie存储的经纬度变量
解决方案
核心错误原因
- Cookie键名大小写不匹配:存储时使用
Lat、Long作为键名,读取时误用lat、long,导致读取不到有效数值 - Cookie读取的返回值为字符串类型,Google Maps要求经纬度参数必须为数字类型,直接赋值会触发类型错误
- 第一段代码存在无效属性调用:
position.coords.Longitude为错误写法,标准属性为小写longitude,且无必要重复存储 - 模板字符串需用反引号包裹才会解析变量,直接在对象字面量中写
${xxx}不会生效
修正后完整代码
1. 获取当前位置代码
<html> <body> <p>Click to get your current coordinates.</p> <button id="clickButton" onclick="getLocation()">Get Your Current Location and after refresh this page...</button> <p id="demo"></p> <script> setInterval(function(){ // 每秒自动触发一次位置获取 document.getElementById('clickButton').click(); }, 1000); var x = document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude; // 统一Cookie键名,后续读取保持一致 document.cookie = "Long = " + position.coords.longitude; document.cookie = "Lat = " + position.coords.latitude; } </script> </body> </html>
2. 地图点位展示代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>My Google Map</title> <style> #map{ height:400px; width:100%; } </style> </head> <body> <h1>My Google Map</h1> <div id="map"></div> <script> // 读取Cookie时转换为数字类型,键名和存储时保持大小写一致 var lati = Number(getCookie("Lat")); var longi = Number(getCookie("Long")); function initMap(){ // 兜底逻辑:如果未读取到有效经纬度,使用默认值避免地图加载失败 if(isNaN(lati) || isNaN(longi)) { lati = 37.128285; longi = -8.539157; } // Map options var options = { zoom:8, // 直接传入数字类型的经纬度变量即可 center:{lat: lati, lng: longi} } // New map var map = new google.maps.Map(document.getElementById('map'), options); // Listen for click on map google.maps.event.addListener(map, 'click', function(event){ // Add marker addMarker({coords:event.latLng}); }); // Array of markers var markers = [ { // driver1点位直接使用读取到的经纬度变量 coords:{lat: lati, lng: longi}, iconImage:'https://www.nicetaxi.eu/Taxi-icon.png', content:'<h1>driver 1</h1>' }, { coords:{lat:37.128285,lng:-8.539157}, content:'<h1>driver 2</h1>' }, { coords:{lat:37.128285,lng:-8.539159} } ]; // Loop through markers for(var i = 0;i < markers.length;i++){ // Add marker addMarker(markers[i]); } // Add Marker Function function addMarker(props){ var marker = new google.maps.Marker({ position:props.coords, map:map, //icon:props.iconImage }); // Check for customicon if(props.iconImage){ // Set icon image marker.setIcon(props.iconImage); } // Check content if(props.content){ var infoWindow = new google.maps.InfoWindow({ content:props.content }); marker.addListener('click', function(){ infoWindow.open(map, marker); }); } } } function getCookie(name) { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) return parts.pop().split(';').shift(); } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBg8mazOCFsHlsOfTClG9Cugb1ddBPfldU&callback=initMap"> </script> </body> </html>
内容的提问来源于stack exchange,提问作者wizards supports
相关产品推荐
相关产品推荐

