地理编码
- 地址 -> 坐标
Geocoder.getLocation
,使用地理编码接口,根据地址转获取经纬度位置。
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.12&key=您申请的key值&plugin=AMap.Geocoder"></script>
var map = new AMap.Map("container", {
resizeEnable: true
});
var geocoder,marker;
function geoCode() {
if(!geocoder){
geocoder = new AMap.Geocoder({
city: "010", //城市设为北京,默认:"全国"
});
}
var address = document.getElementById('address').value; // 即用户输入的地址值value
geocoder.getLocation(address, function(status, result) {
if (status === 'complete'&&result.geocodes.length) {
var lnglat = result.geocodes[0].location
document.getElementById('lnglat').value = lnglat;
if(!marker){
marker = new AMap.Marker();
map.add(marker);
}
marker.setPosition(lnglat);
map.setFitView(marker);
}else{alert(JSON.stringify(result))}
});
// addresses Array 批量地理编码转换
// geocoder.getLocation(addresses, function(status, result) {
// if (status === 'complete'&&result.geocodes.length) {
// for(var i=0;i<result.geocodes.length;i+=1){
// var marker = new AMap.Marker({
// position: result.geocodes[i].location
// });
// markers.push(marker);
// }
// map.add(markers);
// map.setFitView(markers);
// }
// });
}
document.getElementById("geo").onclick = geoCode; // 点击切换
document.getElementById('address').onkeydown = function(e) { // 输入完成后按enter切换
if (e.keyCode === 13) {
geoCode();
return false;
}
return true;
}
- 坐标 -> 地址
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.12&key=您申请的key值&plugin=AMap.Geocoder"></script>
function regeoCode() {
if(!geocoder){
geocoder = new AMap.Geocoder({
city: "010", //城市设为北京,默认:“全国”
radius: 1000 //范围,默认:500
});
}
var lnglat = document.getElementById('lnglat').value.split(',');
if(!marker){
marker = new AMap.Marker();
map.add(marker);
}
marker.setPosition(lnglat);
geocoder.getAddress(lnglat, function(status, result) {
if (status === 'complete'&&result.regeocode) {
var address = result.regeocode.formattedAddress;
document.getElementById('address').value = address;
}else{alert(JSON.stringify(result))}
});
}
map.on('click',function(e){ // 地图点击切换
document.getElementById('lnglat').value = e.lnglat;
regeoCode();
})
document.getElementById("regeo").onclick = regeoCode; // 按钮点击切换
一次查询多个经纬度的地址
var map = new AMap.Map("container", {
resizeEnable: true
});
var posDiv = document.getElementById('postions');
var lnglats = [],markers = [];
map.on('click',function(e){
if(lnglats.length < 10){
lnglats.push(e.lnglat);
var index = lnglats.length;
var marker = new AMap.Marker({
content:'<div class="mark">'+lnglats.length+'</div>',
position: e.lnglat
});
markers.push(marker);
map.add(marker);
var newItem =
'<div class="input-item">'+
'<div class="input-item-prepend"><span class="input-item-text" >'+e.lnglat+'</span></div>'+
'<input id="address'+index+'" disabled type="text">'+
'</div>';
document.getElementById('blank_item').insertAdjacentHTML('beforebegin',newItem)
}
})
var geocoder;
function regeoCode() {
if(!geocoder){
geocoder = new AMap.Geocoder({
city: "010", //城市设为北京,默认:“全国”
radius: 1000 //范围,默认:500
});
}
geocoder.getAddress(lnglats, function(status, result) {
var address = []
if (status === 'complete'&&result.regeocodes.length) {
for(var i=0;i< result.regeocodes.length;i+=1){
document.getElementById("address"+(i+1)).value = result.regeocodes[i].formattedAddress
}
}else{
alert(JSON.stringify(result))
}
});
}
function clear(){
map.remove(markers);
markers = [];
lnglats = []
posDiv.innerHTML='<div id="blank_item" class="input-item"><div class="input-item-prepend"><span class="input-item-text">点击地图添加经纬度</span></div><input type="text"></div>';
}
document.getElementById("regeo").onclick = regeoCode;
document.getElementById("clear").onclick = clear;
行政区查询
- 行政区边界查询
使用DistrictSearch.search
获取某个行政区的边界信息,并绘制行政区划边界。
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.12&key=您申请的key值&plugin=AMap.DistrictSearch"></script>
//初始化地图对象,加载地图
var map = new AMap.Map("container", {
resizeEnable: true,
center: [116.397428, 39.90923],//地图中心点
zoom: 10 //地图显示的缩放级别
});
var district = null;
var polygons=[];
function drawBounds() {
//加载行政区划插件
if(!district){
//实例化DistrictSearch
var opts = {
subdistrict: 0, //获取边界不需要返回下级行政区
extensions: 'all', //返回行政区边界坐标组等具体信息
level: 'district' //查询行政级别为 市
};
district = new AMap.DistrictSearch(opts);
}
//行政区查询
// 使用setLevel修改查询级别
district.setLevel(document.getElementById('level').value)
district.search(document.getElementById('district').value, function(status, result) {
map.remove(polygons)//清除上次结果
polygons = [];
var bounds = result.districtList[0].boundaries;
if (bounds) {
for (var i = 0, l = bounds.length; i < l; i++) {
//生成行政区划polygon
var polygon = new AMap.Polygon({
strokeWeight: 1,
path: bounds[i],
fillOpacity: 0.4,
fillColor: '#80d8ff',
strokeColor: '#0091ea'
});
polygons.push(polygon);
}
}
map.add(polygons)
map.setFitView(polygons);//视口自适应
});
}
document.getElementById('draw').onclick = drawBounds;
- 下属行政区查询
使用DistrictSearch
逐级别依次搜索下级行政区的信息,并生成下拉列表。
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.12&key=您申请的key值&plugin=AMap.DistrictSearch"></script>
var map, district, polygons = [], citycode;
var citySelect = document.getElementById('city');
var districtSelect = document.getElementById('district');
var areaSelect = document.getElementById('street');
map = new AMap.Map('container', {
resizeEnable: true,
center: [116.30946, 39.937629],
zoom: 3
});
//行政区划查询
var opts = {
subdistrict: 1, //返回下一级行政区
showbiz:false //最后一级返回街道信息
};
district = new AMap.DistrictSearch(opts);//注意:需要使用插件同步下发功能才能这样直接使用
district.search('中国', function(status, result) {
if(status=='complete'){
getData(result.districtList[0]);
}
});
function getData(data,level) {
var bounds = data.boundaries;
if (bounds) {
for (var i = 0, l = bounds.length; i < l; i++) {
var polygon = new AMap.Polygon({
map: map,
strokeWeight: 1,
strokeColor: '#0091ea',
fillColor: '#80d8ff',
fillOpacity: 0.2,
path: bounds[i]
});
polygons.push(polygon);
}
map.setFitView();//地图自适应
}
//清空下一级别的下拉列表
if (level === 'province') {
citySelect.innerHTML = '';
districtSelect.innerHTML = '';
areaSelect.innerHTML = '';
} else if (level === 'city') {
districtSelect.innerHTML = '';
areaSelect.innerHTML = '';
} else if (level === 'district') {
areaSelect.innerHTML = '';
}
var subList = data.districtList;
if (subList) {
var contentSub = new Option('--请选择--');
var curlevel = subList[0].level;
var curList = document.querySelector('#' + curlevel);
curList.add(contentSub);
for (var i = 0, l = subList.length; i < l; i++) {
var name = subList[i].name;
var levelSub = subList[i].level;
var cityCode = subList[i].citycode;
contentSub = new Option(name);
contentSub.setAttribute("value", levelSub);
contentSub.center = subList[i].center;
contentSub.adcode = subList[i].adcode;
curList.add(contentSub);
}
}
}
function search(obj) {
//清除地图上所有覆盖物
for (var i = 0, l = polygons.length; i < l; i++) {
polygons[i].setMap(null);
}
var option = obj[obj.options.selectedIndex];// options是所有选项的element集合
var keyword = option.text; //关键字
var adcode = option.adcode;
district.setLevel(option.value); //行政区级别
district.setExtensions('all');
//行政区查询
//按照adcode进行查询可以保证数据返回的唯一性
district.search(adcode, function(status, result) {
if(status === 'complete'){
getData(result.districtList[0],obj.id);
}
});
}
function setCenter(obj){
map.setCenter(obj[obj.options.selectedIndex].center)
}
公交信息查询
- 使用
AMap.StationSearch
和『站点关键字』进行公交站点查询
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.12&key=您申请的key值&plugin=AMap.StationSearch"></script>
function stationSearch() {
var stationKeyWord = document.getElementById('stationKeyWord').value
if(!stationKeyWord) return
//实例化公交站点查询类
var station = new AMap.StationSearch({
pageIndex: 1, //页码
pageSize: 60, //单页显示结果条数
city: '010' //确定搜索城市
});
station.search(stationKeyWord, function(status, result) {
if (status === 'complete' && result.info === 'OK') {
stationSearch_CallBack(result); // 处理获取到的信息 生成marker
} else {
document.getElementById('tip').innerHTML = JSON.stringify(result);
}
});
}
/*公交站点查询返回数据解析*/
function stationSearch_CallBack(searchResult) {
var stationArr = searchResult.stationInfo;
var searchNum = stationArr.length;
if (searchNum > 0) {
document.getElementById('tip').innerHTML = '查询结果:共' + searchNum + '个相关站点';
map.clearMap(); // 清楚所有的marker
for (var i = 0; i < searchNum; i++) {
var marker = new AMap.Marker({
icon:new AMap.Icon({
image:'https://a.amap.com/jsapi_demos/static/resource/img/pin.png',
size:new AMap.Size(32,32),
imageSize:new AMap.Size(32,32)
}),
offset:new AMap.Pixel(-16,-32),
position: stationArr[i].location,
map: map,
title: stationArr[i].name // 鼠标移入的文字站名提示
});
// 也可以自定义信息窗体
// marker.info = new AMap.InfoWindow({
// content: stationArr[i].name,
// offset: new AMap.Pixel(0, -30)
// });
// marker.on('mouseover', function(e) {
// e.target.info.open(map, e.target.getPosition())
// })
}
map.setFitView();
}
}
document.getElementById('search').onclick = stationSearch;
- 使用
AMap.LineSearch
进行公交线路查询
/*
* 该示例主要流程分为三个步骤
* 1. 首先调用公交路线查询服务(lineSearch)
* 2. 根据返回结果解析,输出解析结果(lineSearch_Callback)
* 3. 在地图上绘制公交线路()
*/
var map = new AMap.Map("container", {
resizeEnable: true,
center: [116.397428, 39.90923],//地图中心点
zoom: 13 //地图显示的缩放级别
});
var linesearch;
/*公交线路查询*/
function lineSearch() {
var busLineName = document.getElementById('BusLineName').value;
if(!busLineName) return;
//实例化公交线路查询类,只取回一条路线
if(!linesearch){
linesearch = new AMap.LineSearch({
pageIndex: 1,
city: '北京',
pageSize: 1,
extensions: 'all'
});
}
//搜索“536”相关公交线路
linesearch.search(busLineName, function(status, result) {
map.clearMap()
if (status === 'complete' && result.info === 'OK') {
lineSearch_Callback(result);
} else {
alert(result);
}
});
}
/*公交路线查询服务返回数据解析概况*/
function lineSearch_Callback(data) {
var lineArr = data.lineInfo;
var lineNum = data.lineInfo.length;
if (lineNum == 0) {
} else {
for (var i = 0; i < lineNum; i++) {
var pathArr = lineArr[i].path;
var stops = lineArr[i].via_stops;
var startPot = stops[0].location;
var endPot = stops[stops.length - 1].location;
if (i == 0) //作为示例,只绘制一条线路
drawbusLine(startPot, endPot, pathArr);
}
}
}
/*绘制路线*/
function drawbusLine(startPot, endPot, BusArr) {
//绘制起点,终点
new AMap.Marker({
map: map,
position: startPot, //基点位置
icon: "https://webapi.amap.com/theme/v1.3/markers/n/start.png",
zIndex: 10
});
new AMap.Marker({
map: map,
position: endPot, //基点位置
icon: "https://webapi.amap.com/theme/v1.3/markers/n/end.png",
zIndex: 10
});
//绘制乘车的路线
busPolyline = new AMap.Polyline({
map: map,
path: BusArr,
strokeColor: "#09f",//线颜色
strokeOpacity: 0.8,//线透明度
isOutline:true,
outlineColor:'white',
strokeWeight: 6//线宽
});
map.setFitView();
}
lineSearch();
document.getElementById('search').onclick = lineSearch;
定位
使用CitySearch.getLocalCity
可根据IP
进行城市级定位,获得用户当前所在城市信息,适用于PC
端以及GPS
信号不佳的场景。
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.12&key=您申请的key值&plugin=AMap.CitySearch"></script>
var map = new AMap.Map("container", {
resizeEnable: true,
center: [116.397428, 39.90923],
zoom: 13
});
//获取用户所在城市信息
function showCityInfo() {
//实例化城市查询类
var citysearch = new AMap.CitySearch();
//自动获取用户IP,返回当前城市
citysearch.getLocalCity(function(status, result) {
if (status === 'complete' && result.info === 'OK') {
if (result && result.city && result.bounds) {
var cityinfo = result.city;
var citybounds = result.bounds;
document.getElementById('info').innerHTML = '您当前所在城市:'+cityinfo;
//地图显示当前城市
map.setBounds(citybounds); // 指定当前地图显示范围,参数bounds为指定的范围。
}
} else {
document.getElementById('info').innerHTML = result.info;
}
});
}
showCityInfo();
Map
实例初始化时,不设定center
时,API
将根据用户 IP
自动匹配地图中心点到用户所在城市的中心。
// 初始化地图时,若center属性缺省,地图默认定位到用户所在城市的中心
var map = new AMap.Map('container', {
resizeEnable: true
});
document.getElementById('adcode').innerHTML='当前城市adcode:'+map.getAdcode()+'<br>'+
'当前中心点:'+map.getCenter()
使用Geolocation.getCurrentPosition
获取当前位置,可用于依赖于于用户定位的场景。
AMap.plugin('AMap.Geolocation', function() {
var geolocation = new AMap.Geolocation({
enableHighAccuracy: true,//是否使用高精度定位,默认:true
timeout: 10000, //超过10秒后停止定位,默认:5s
buttonPosition:'RT', //定位按钮的停靠位置
buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
});
map.addControl(geolocation);
geolocation.getCurrentPosition(function(status,result){
if(status=='complete'){
onComplete(result)
}else{
onError(result)
}
});
});
//解析定位结果
function onComplete(data) {
document.getElementById('status').innerHTML='定位成功'
var str = [];
str.push('定位结果:' + data.position);
str.push('定位类别:' + data.location_type);
if(data.accuracy){
str.push('精度:' + data.accuracy + ' 米');
}//如为IP精确定位结果则没有精度信息
str.push('是否经过偏移:' + (data.isConverted ? '是' : '否'));
document.getElementById('result').innerHTML = str.join('<br>');
}
通过给Geolocation
设定相关属性,可以自定义定位按钮、定位点和精度圆的显示样式以及是否显示
var map = new AMap.Map('container', {
resizeEnable: true
});
var options = {
'showButton': true,//是否显示定位按钮
'buttonPosition': 'LB',//定位按钮的位置
/* LT LB RT RB */
'buttonOffset': new AMap.Pixel(10, 20),//定位按钮距离对应角落的距离
'showMarker': true,//是否显示定位点
'markerOptions':{//自定义定位点样式,同Marker的Options
'offset': new AMap.Pixel(-18, -36),
'content':'<img src="https://a.amap.com/jsapi_demos/static/resource/img/user.png" style="width:36px;height:36px"/>'
},
'showCircle': true,//是否显示定位精度圈
'circleOptions': {//定位精度圈的样式
'strokeColor': '#0093FF',
'noSelect': true,
'strokeOpacity': 0.5,
'strokeWeight': 1,
'fillColor': '#02B0FF',
'fillOpacity': 0.25
}
}
AMap.plugin(["AMap.Geolocation"], function() {
var geolocation = new AMap.Geolocation(options);
map.addControl(geolocation);
geolocation.getCurrentPosition()
});
天气预报
使用Weather
插件,获取指定地区的天气信息,可用于天气查询等场景。
AMap.plugin('AMap.Weather', function() {
var weather = new AMap.Weather();
//查询实时天气信息, 查询的城市到行政级别的城市,如朝阳区、杭州市
weather.getLive('朝阳区', function(err, data) {
if (!err) {
var str = [];
str.push('<h4 >实时天气' + '</h4><hr>');
str.push('<p>城市/区:' + data.city + '</p>');
str.push('<p>天气:' + data.weather + '</p>');
str.push('<p>温度:' + data.temperature + '℃</p>');
str.push('<p>风向:' + data.windDirection + '</p>');
str.push('<p>风力:' + data.windPower + ' 级</p>');
str.push('<p>空气湿度:' + data.humidity + '</p>');
str.push('<p>发布时间:' + data.reportTime + '</p>');
var marker = new AMap.Marker({map: map, position: map.getCenter()});
// 可使用map.setCity(val);设置当前行政区
// 可使用DistrictSearch.search 获取行政区的信息
var infoWin = new AMap.InfoWindow({
content: '<div class="info" style="position:inherit;margin-bottom:0;">'+str.join('')+'</div><div class="sharp"></div>',
isCustom:true,
offset: new AMap.Pixel(0, -37)
});
infoWin.open(map, marker.getPosition());
marker.on('mouseover', function() {
infoWin.open(map, marker.getPosition());
});
}
});
//未来4天天气预报
weather.getForecast('朝阳区', function(err, data) {
if (err) {return;}
var str = [];
for (var i = 0,dayWeather; i < data.forecasts.length; i++) {
dayWeather = data.forecasts[i];
str.push(dayWeather.date+' <span class="weather">'+dayWeather.dayWeather+'</span> '+ dayWeather.nightTemp + '~' + dayWeather.dayTemp + '℃');
}
document.getElementById('forecast').innerHTML = str.join('<br>');
});
});
网友评论