百度地图、高德地图使用
一、【百度官网】https://lbsyun.baidu.com/
开发文档:https://lbsyun.baidu.com/index.php?title=jspopularGL
二、百度地图使用例子
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
body, html{width: 100%;height: 100%;margin:0;font-family:"微软雅黑";font-size:14px;}
#allmap {width:100%;height:500px;}
</style>
<script src="jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你的钥匙"></script>
<title>逆地址解析</title>
</head>
<body>
<div id="allmap"></div>
<div id="r-result">请输入:<input type="text" id="suggestId" size="20" value="" style="width:150px;" />
</div>
<div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto;"></div>
</body>
</html>
<script type="text/javascript">
// 百度地图API功能
var map = new BMap.Map("allmap");
//默认一个中心坐标
map.centerAndZoom(new BMap.Point(107.164226, 31.859637), 5);
map.addControl(new BMap.NavigationControl());
map.addControl(new BMap.NavigationControl());
map.addControl(new BMap.ScaleControl());
map.addControl(new BMap.OverviewMapControl());
map.addControl(new BMap.MapTypeControl());
//map.centerAndZoom("盐城", 15); // 初始化地图,设置城市和地图级别。
//map.setCurrentCity("盐城"); // 仅当设置城市信息时,MapTypeControl的切换功能才能可用
//定位拾坐标
var geoc = new BMap.Geocoder();
//开启滚轮缩放地图
map.enableScrollWheelZoom();
var geolocation = new BMap.Geolocation();
// 开启SDK辅助定位
geolocation.enableSDKLocation();
geolocation.getCurrentPosition(function (r) {
if (this.getStatus() == BMAP_STATUS_SUCCESS) {
var mk = new BMap.Marker(r.point);
map.addOverlay(mk);
map.panTo(r.point);
//alert('您的位置:' + r.point.lng + ',' + r.point.lat);
var pt = r.point;
map.panTo(pt);//移动地图中心点
geoc.getLocation(pt, function (rs) {
var addComp = rs.addressComponents;
});
}
});
var myValue;
//点击坐标事件
map.addEventListener("click", function (e) {
var pt = e.point;
//移除原有的标注
map.clearOverlays();
var pointMarker = new BMap.Point(e.point.lng, e.point.lat); // 创建标注的坐标
addMarker(pointMarker);
geoc.getLocation(pt, function (rs) {
var addComp = rs.addressComponents;
myValue = addComp.province + addComp.city + addComp.district +addComp.street + addComp.streetNumber;
G("searchResultPanel").innerHTML = "click<br /><br />myValue = " + myValue;
G("suggestId").value = myValue;
});
});
//添加标注
function addMarker(point) {
var myIcon = new BMap.Icon("../../images/map-marker.png", new BMap.Size(25, 25), {
offset: new BMap.Size(10, 25), // 指定定位位置
imageOffset: 0 // 设置图片偏移
});
var marker = new BMap.Marker(point, { icon: myIcon });
map.addOverlay(marker);
}
var ac = new BMap.Autocomplete( //建立一个自动完成的对象
{
"input": "suggestId"
, "location": map
});
ac.addEventListener("onhighlight", function (e) { //鼠标放在下拉列表上的事件
var str = "";
var _value = e.fromitem.value;
var value = "";
if (e.fromitem.index > -1) {
value = _value.province + _value.city + _value.district + _value.street + _value.business;
}
str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
value = "";
if (e.toitem.index > -1) {
_value = e.toitem.value;
value = _value.province + _value.city + _value.district + _value.street + _value.business;
}
str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
G("searchResultPanel").innerHTML = str;
});
var myValue;
ac.addEventListener("onconfirm", function (e) { //鼠标点击下拉列表后的事件
var _value = e.item.value;
myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
setPlace();
});
function setPlace() {
map.clearOverlays(); //清除地图上所有覆盖物
function myFun() {
var pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
map.centerAndZoom(pp, 18);
map.addOverlay(new BMap.Marker(pp)); //添加标注
}
var local = new BMap.LocalSearch(map, { //智能搜索
onSearchComplete: myFun
});
local.search(myValue);
}
function G(id) {
return document.getElementById(id);
}
</script>
- BMap获取用户当前经纬度和详细地理位置
https://blog.csdn.net/m0_46149348/article/details/129532955
https://www.cnblogs.com/telwanggs/p/16795774.html
- 地图添加标注
https://www.cnblogs.com/Fooo/p/6893793.html
比较全的事例
https://blog.csdn.net/stc_ljc/article/details/129071908
三、高德官网开发文档:
注意:高德2.0之前的版本,跟2.0是不一样的。区分:https://blog.csdn.net/weixin_47359038/article/details/131982163
https://lbs.amap.com/api/javascript-api-v2/changelog
https://lbs.amap.com/demo/amap-ui/demos/amap-ui-pathsimplifier/simple-demo
比较全的事例:https://www.jb51.net/article/268963.htm
高德使用代码:需要引入map.js、initMap.js
引入组件,具体实现在map.js中
<template>
<div>
<!-- <label>消息管理</label> -->
<div style="margin-top: 20px">
<div style="height:800px;">
<div id="all" style="height:100%">
<div class="posInput">
<el-input style="width:100%"
id="tipinput"
class="form-control input-style"
type="text"
placeholder="请输入搜索地址"
prefix-icon="el-icon-search"
v-model="formatAdress"
>
</el-input>
</div>
<div id="allmap"></div>
<div class="posSubmit">
<el-form ref="form" label-width="85px" >
<div class="btn_box" >
<el-form-item label="经度:" >
<el-input style="width:400px" disabled class="form-control input-style" type="text" v-model="longitude"> </el-input>
</el-form-item>
<el-form-item label="纬度:" >
<el-input style="width:400px" disabled class="form-control input-style" type="text" v-model="latitude"> </el-input>
</el-form-item>
</div>
</el-form>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
//这里可以导入其他文件(比如:组件,工具js,第三方插件js,json文件,图片文件等等)
//例如:import 《组件名称》 from '《组件路径》';
import {
init,
initScaleTools,
searchAutocomplete,
getAddressByLngLat
} from '../uitils/map'
export default {
//import引入的组件需要注入到对象中才能使用
components: {},
props: {},
data() {
//这里存放数据
return {
map: null,
marker: null,
startSeacrh: [],
stratInfo: {},
dprops: {
zoom: 15
},
formatAdress: '',
longitude: '', // 经度
latitude: '', // 纬度
};
},
//监听属性 类似于data概念
computed: {},
//监控data中的数据变化
watch: {},
mounted () {
this.initMap()
},
methods: {
initMap () {
const that = this
init('allmap', that.dprops).then(AMap => {
that.map = AMap
that.map.on('click', that.clickHandler) // 地图点击事件 可获取经纬度等信息
initScaleTools(that.map, true, false)
searchAutocomplete(that.map, 'tipinput', function (event) {
that.handleStartSelect(event)
})
}).catch(err => {
this.$message.error(err)
console.info(err);
})
},
clickHandler (event) {
console.log(event, '起点经纬度 [lng,lat]')
if (event.lnglat === '') {
this.$message({
type: 'warning',
message: '该地点无经纬度数据,请输入具体一点的地点!',
duration: 5 * 1000
})
return
}
if (this.marker) {
this.map.remove(this.marker)
this.marker = null
}
this.startSeacrh = []
this.startSeacrh = [event.lnglat.lng, event.lnglat.lat]
this.marker = new AMap.Marker({
position: this.startSeacrh
})
this.map.add(this.marker);
this.map.setCenter(this.startSeacrh);
this.longitude = event.lnglat.lng;
this.latitude = event.lnglat.lat;
let that = this;
getAddressByLngLat(this.startSeacrh, function (status, result) {
if (status === 'complete') {
that.formatAdress = result.regeocode.formattedAddress
let adrComponent = result.regeocode.addressComponent
that.stratInfo = {
district: adrComponent.province,
address: adrComponent.district,
name: adrComponent.township + adrComponent.street + adrComponent.streetNumber,
fullAdr: result.regeocode.formattedAddress
}
}
})
},
handleStartSelect (event) {
console.log(event, '起点经纬度 [lng,lat]')
if (event.poi.location === '') {
this.$message({
type: 'warning',
message: '该地点无经纬度数据,请输入具体一点的地点!',
duration: 5 * 1000
})
return
}
if (this.marker) {
this.map.remove(this.marker)
this.marker = null
}
this.startSeacrh = []
this.startSeacrh = [event.poi.location.lng, event.poi.location.lat]
this.formatAdress = event.poi.district + event.poi.address + event.poi.name
this.longitude = event.poi.location.lng
this.latitude = event.poi.location.lat
console.log('long:'+this.longitude+";latitude:"+this.latitude)
this.marker = new AMap.Marker({
position: this.startSeacrh
})
this.map.add(this.marker)
this.map.setCenter(this.startSeacrh)
this.stratInfo = {
district: event.poi.district,
address: event.poi.address,
name: event.poi.name,
fullAdr: this.formatAdress
}
}
},
beforeCreate() { }, //生命周期 - 创建之前
//生命周期 - 创建完成(可以访问当前this实例)
created() { },
beforeMount() { }, //生命周期 - 挂载之前
//生命周期 - 挂载完成(可以访问DOM元素)
beforeUpdate() { }, //生命周期 - 更新之前
updated() { }, //生命周期 - 更新之后
beforeDestroy() { }, //生命周期 - 销毁之前
destroyed() { }, //生命周期 - 销毁完成
activated() { }, //如果页面有keep-alive缓存功能,这个函数会触发
};
</script>
<style scoped>
#all{
position: relative;
}
#allmap{
width: 100%; height: calc(100% - 50px);
font-family: "微软雅黑";
}
.posInput{
position: absolute;
z-index: 1;
width: 80%;
margin-top: 20px; margin-left: 10%;
}
.posSubmit{
position: absolute; z-index: 1; bottom: 0;
margin-left: 5%;
width: 90%;
display: flex; justify-content: flex-start; align-items: center;
}
.btn_box{
width: 100%;
height: 100%;
display: flex; ; align-items: center;
}
::v-deep .el-form-item{
margin-bottom: 0 !important;
}
</style>
<template>
<div>
<!-- <label>消息管理</label> -->
<div style="margin-top: 20px">
<div style="height: 800px">
<div id="all" style="height: 100%">
<div id="allmap"></div>
</div>
</div>
</div>
<div id="routes-container">
</div>
</div>
</template>
<script>
// import AMap from "vue-amap";
//这里可以导入其他文件(比如:组件,工具js,第三方插件js,json文件,图片文件等等)
//例如:import 《组件名称》 from '《组件路径》';
import {
init,
initScaleTools,
searchAutocomplete,
getAddressByLngLat,
} from "../uitils/map";
export default {
//import引入的组件需要注入到对象中才能使用
components: {},
props: {},
data() {
//这里存放数据
return {
map: null,
marker: null,
startSeacrh: [],
stratInfo: {},
dprops: {
zoom: 4,
},
formatAdress: "",
longitude: "", // 经度
latitude: "", // 纬度
pathName:"路线:北京-乌鲁木齐",
TrackingData:[
[116.405289, 39.904987],
[113.964458, 40.54664],
[111.47836, 41.135964],
[108.949297, 41.670904],
[106.380111, 42.149509],
[103.774185, 42.56996],
[101.135432, 42.930601],
[98.46826, 43.229964],
[95.777529, 43.466798],
[93.068486, 43.64009],
[90.34669, 43.749086],
[87.61792, 43.793308],
// [120.68034640842014, 31.16948025173611],
// [120.68399956597223, 31.139243706597224],
// [120.04279758029514, 30.947743326822916],
// [120.04279758029514, 30.947743326822916],
// [119.15660725911458, 30.954883626302085],
// [118.58166965060764, 31.13359076605903],
// [118.58166965060764, 31.252462811790856],
// [118.19280495018312, 31.252462811790856]
]
};
},
//监听属性 类似于data概念
computed: {},
//监控data中的数据变化
watch: {},
mounted() {
this.initMap();
},
methods: {
initMap() {
const that = this;
init("allmap", that.dprops)
.then((AMap) => {
that.map = AMap;
// that.map.on('click', that.clickHandler) // 地图点击事件 可获取经纬度等信息
initScaleTools(that.map, true, false);
// searchAutocomplete(that.map, 'tipinput', function (event) {
// that.handleStartSelect(event)
// })
AMapUI.load(["ui/misc/PathSimplifier", "lib/$"], function (PathSimplifier, $) {
if (!PathSimplifier.supportCanvas) {
alert("当前环境不支持 Canvas!");
return;
}
var pathSimplifierIns = new PathSimplifier({
zIndex: 100,
//autoSetFitView:false,
map: that.map, //所属的地图实例
getPath: function (pathData, pathIndex) {
return pathData.path;
},
getHoverTitle: function (pathData, pathIndex, pointIndex) {
if (pointIndex >= 0) {
//point
return (
pathData.name + ",点:" + pointIndex + "/" + pathData.path.length
);
}
return pathData.name + ",点数量" + pathData.path.length;
},
renderOptions: {
renderAllPointsIfNumberBelow: 100, //绘制路线节点,如不需要可设置为-1
},
});
window.pathSimplifierIns = pathSimplifierIns;
//设置数据
pathSimplifierIns.setData([
{
name: that.pathName,
path: that.TrackingData,
},
]);
function onload() {
pathSimplifierIns.renderLater();
}
function onerror(e) {
alert("图片加载失败!");
}
var pathNavigatorStyles = [
{
width: 16,
height: 24,
content: "defaultPathNavigator",
},
// {
// width: 24,
// height: 24,
// //使用图片
// content: PathSimplifier.Render.Canvas.getImageContent(
// "/static/飞机.png",
// onload,
// onerror
// ),
// },
{
width: 16,
height: 32,
//使用图片
content: PathSimplifier.Render.Canvas.getImageContent(
"/static/Truck.png",
onload,
onerror
),
},
];
function extend(dst) {
if (!dst) {
dst = {};
}
var slist = Array.prototype.slice.call(arguments, 1);
for (var i = 0, len = slist.length; i < len; i++) {
var source = slist[i];
if (!source) {
continue;
}
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
dst[prop] = source[prop];
}
}
}
return dst;
}
var idx = 0;
//对第一条线路(即索引 0)创建一个巡航器
var navg1 = pathSimplifierIns.createPathNavigator(0, {
loop: true, //循环播放
speed: 800000, //巡航速度,单位千米/小时
pathNavigatorStyle:pathNavigatorStyles[1]
// pathNavigatorStyle: extend({}, pathNavigatorStyles[0]),
});
navg1.start();
// function changeNavgContent() {
// //获取到pathNavigatorStyle的引用
// var pathNavigatorStyle = navg1.getStyleOptions();
// //覆盖修改
// extend(
// pathNavigatorStyle,
// pathNavigatorStyles[++idx % pathNavigatorStyles.length]
// );
// //重新绘制
// pathSimplifierIns.renderLater();
// }
// setInterval(changeNavgContent, 500);
});
})
.catch((err) => {
this.$message.error(err);
// console.info(err);
});
},
},
beforeCreate() {}, //生命周期 - 创建之前
//生命周期 - 创建完成(可以访问当前this实例)
created() {},
beforeMount() {}, //生命周期 - 挂载之前
//生命周期 - 挂载完成(可以访问DOM元素)
beforeUpdate() {}, //生命周期 - 更新之前
updated() {}, //生命周期 - 更新之后
beforeDestroy() {}, //生命周期 - 销毁之前
destroyed() {}, //生命周期 - 销毁完成
activated() {}, //如果页面有keep-alive缓存功能,这个函数会触发
};
</script>
<style scoped>
/* #all{
position: relative;
} */
#allmap {
width: 100%;
height: calc(100% - 50px);
font-family: "微软雅黑";
}
::v-deep .el-form-item {
margin-bottom: 0 !important;
}
</style>
高德地图2.0版本规划:
https://i.cnblogs.com/posts/edit;postId=18270358
浙公网安备 33010602011771号