在JavaScript中获取地理位置可以使用HTML5中的Geolocation API,通过navigator.geolocation对象的getCurrentPosition()方法获取当前设备的经纬度信息。
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
console.log("Latitude: " + latitude + " Longitude: " + longitude);
});
} else {
console.log("Geolocation is not supported by this browser.");
}
获取周边信息需要使用地图API,如高德地图API、百度地图API等,这里以高德地图API为例。
首先需要在高德地图开放平台申请开发者账号,并创建一个应用,获取应用的key。
然后在HTML中引入高德地图API的JS文件,并在JS文件中使用AMap.Geocoder对象的getRegeo()方法获取当前位置的周边信息。
// 引入高德地图API的JS文件
// 使用AMap.Geocoder对象的getRegeo()方法获取当前位置的周边信息
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var geocoder = new AMap.Geocoder({
radius: 1000,
extensions: "all"
});
geocoder.getRegeo(new AMap.LngLat(longitude, latitude), function(status, result) {
if (status === "complete" && result.info === "OK") {
console.log(result.regeocode);
}
});
});
} else {
console.log("Geolocation is not supported by this browser.");
}