【使用高德开放平台API和js的Ajax代码实现定位并获得城市的天气情况和经纬度,检索关键词获得周边信息】
以下是使用高德开放平台API和JavaScript实现的Ajax请求来定位城市并获取天气情况的示例代码:
<!DOCTYPE html>
<html>
<head>
<title>获取天气信息</title>
<script src="https://webapi.amap.com/maps?v=1.4.15&key=您的高德API密钥"></script>
<script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>
</head>
<body>
<div id="container" style="width:600px;height:400px;"></div>
<div id="tip"></div>
<script>
var map = new AMap.Map('container', {
resizeEnable: true
});
// 使用HTML5定位
map.plugin('AMap.Geolocation', function() {
var geolocation = new AMap.Geolocation({
enableHighAccuracy: true, // 是否使用高精度定位,默认:true
timeout: 10000 // 超过10秒后停止定位,默认:5s
});
geolocation.getCurrentPosition();
AMap.event.addListener(geolocation, 'complete', onComplete); //返回定位信息
AMap.event.addListener(geolocation, 'error', onError); //返回定位出错信息
});
// 解析定位结果
function onComplete(data) {
var str = ['定位成功'];
str.push('经度:' + data.position.getLng());
str.push('纬度:' + data.position.getLat());
if(data.accuracy){
str.push('精度:' + data.accuracy + ' 米');
}
// 获取天气信息
getWeatherInfo(data.position.getLng(), data.position.getLat());
document.getElementById('tip').innerHTML = str.join('<br>');
}
// 定位出错
function onError(data) {
document.getElementById('tip').innerHTML = '定位失败';
}
// 获取天气信息
function getWeatherInfo(lng, lat) {
var cityInfoUrl = "https://restapi.amap.com/v3/weather/weatherInfo?key=您的高德API密钥&city=" + encodeURIComponent(lng) + "," + encodeURIComponent(lat);
var xhr = new XMLHttpRequest();
xhr.open("GET", cityInfoUrl, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
if(response && response.lives && response.lives.length > 0) {
var live = response.lives[0];
console.log(live);
// 这里可以处理live
评论已关闭