1、H5页面
一个搜索框、一个经纬度接收框
<input class="layui-input" placeholder="地名" name="tipinput" id="tipinput">
<input class="layui-input" value="{$_POST[lnglat]}" readonly placeholder="经纬度" name="lnglat" id="lnglat">
2、地图接收div
<div id="container"></div>
3、引入高德地图js
<script src="https://webapi.amap.com/maps?v=1.4.10&key=你申请的key值&plugin=AMap.Autocomplete">
4、初始化地图
window.onload = function() {
map.plugin(["AMap.ToolBar"], function() {
map.addControl(new AMap.ToolBar());
});
if(location.href.indexOf('&guide=1')!==-1){
map.setStatus({scrollWheel:false})
}
}
var map = new AMap.Map("container", {
resizeEnable: true
});
5、搜索事件
$("#btn").on('click',function () {
AMap.service(["AMap.PlaceSearch"], function() {
var address = document.getElementById("tipinput").value;
//构造地点查询类
var placeSearch = new AMap.PlaceSearch({
pageSize: 5, // 单页显示结果条数
pageIndex: 1, // 页码
// city: "010", // 兴趣点城市
citylimit: true, //是否强制限制在设置的城市内搜索
map: map, // 展现结果的地图实例
// panel: "msg", // 结果列表将在此容器中进行展示。
autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
});
//关键字查询
placeSearch.search(address);
});
});
6、点击地图获取经纬度
//为地图注册click事件获取鼠标点击出的经纬度坐标
AMap.event.addListener(map,'click',function (e) { //添加点击事件,传入对象名,事件名,回调函数
console.log(e);
document.getElementById("lnglat").value = e.lnglat.getLng() + ',' + e.lnglat.getLat();
});
7、搜索框自动搜索
var auto = new AMap.Autocomplete({
input: "tipinput"
});
AMap.event.addListener(auto, "select", select);//注册监听,当选中某条记录时会触发
function select(e) {
if (e.poi && e.poi.location) {
map.setZoom(15);
map.setCenter(e.poi.location);
}
}