【前端】html5获取经纬度,百度api获取街区名,并使用JS保存进cookie
引用js
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=百度申请的ak"></script>
//html5获取经纬度 function GetLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { alert("Geolocation is not supported by this browser."); } } //百度api获取街区名 function showPosition(position) { var origins = position.coords.latitude + "," + position.coords.longitude; var myGeo = new BMap.Geocoder(); var point = new BMap.Point(position.coords.longitude, position.coords.latitude); myGeo.getLocation(point, function (rs) { var addComp = rs.addressComponents; setCookie(‘c_district’,rs.addressComponents.district,1); }); } //JS保存cookie function setCookie(c_name, value, expiredays) { var exdate = new Date() exdate.setDate(exdate.getDate() + expiredays) document.cookie = c_name + "=" + value + ';path=/' + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) } //获取cookie function getCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "=") if (c_start != -1) { c_start = c_start + c_name.length + 1 c_end = document.cookie.indexOf(";", c_start) if (c_end == -1) c_end = document.cookie.length return (document.cookie.substring(c_start, c_end)); } } return "" }