百度地图关键字搜索并拾取坐标
程序员文章站
2022-06-01 10:39:22
...
<script src="//api.map.baidu.com/api?v=2.0&ak={:C('BAIDU_MAP_KEY_BROWER')}"></script>
<form class="layui-form">
<div class="layui-form-item">
<div class="layui-form-label">地图</div>
<div class="layui-input-block map-container">
<div id="map"></div>
<div id="r-result"></div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<div
class="layui-inline"
style="width:300px;"
>
<input
name="lnglat"
value="{$row[ent_maplng]},{$row[ent_maplat]}"
class="layui-input"
placeholder="经纬度坐标"
/>
</div>
<div class="layui-inline">
<input
id="map_keyword"
class="layui-input"
placeholder="搜索关键字"
/>
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button
class="layui-btn"
lay-submit
lay-filter="*"
>保存</button>
</div>
</div>
</form>
layui.use(['form', 'layer', 'jquery'], function () {
var form = layui.form
, layer = layui.layer
, $ = layui.jquery
var map = new BMap.Map('map')
//添加比例尺
map.addControl(new BMap.NavigationControl())
//设置中心点及缩放
const center_lng = '{$row[ent_maplng]}' || 117.175815
const center_lat = '{$row[ent_maplat]}' || 35.096036
map.centerAndZoom(new BMap.Point(center_lng, center_lat), 17)
var marker
//初始化坐标点
addMarker(center_lng, center_lat)
//监听鼠标点击
map.addEventListener("click", function (e) {
//手动定义坐标
addMarker(e.point.lng, e.point.lat)
})
function addMarker(lng, lat) {
map.removeOverlay(marker) //清除覆盖物
if (lng && lat) {
var point = new BMap.Point(lng, lat)
marker = new BMap.Marker(point) //创建标注
map.addOverlay(marker) //将标注添加到地图中
marker.setAnimation(BMAP_ANIMATION_BOUNCE) //跳起来
$('[name=lnglat]').val(lng + "," + lat)
}
}
//定义地图搜索
var local = new BMap.LocalSearch(map, {
renderOptions: {
map: map
, panel: "r-result"
}
, onInfoHtmlSet: function (res) {
//通过搜索结果标记坐标
addMarker(res.point.lng, res.point.lat)
}
})
//通过关键字搜索
$('#map_keyword').on('input propertychange', function () {
local.search($(this).val())
}).triggerHandler('input')
form.on('submit(*)', function (e) {
var lnglat = e.field.lnglat
, ent_maplng = _.split(lnglat, ',')[0]
, ent_maplat = _.split(lnglat, ',')[1]
if (!ent_maplng || !ent_maplat) {
layer.msg('坐标拾取有误', { icon: 5 })
return false
}
var data = {
ent_maplng: ent_maplng
, ent_maplat: ent_maplat
}
$.post('__CONTROLLER__/ajax_store', data, function (res) {
if (res.status == 1) {
layer.msg('保存成功', { icon: 6 })
} else {
layer.msg(res.error, { icon: 5 })
}
})
return false
})
})
.map-container {
display: flex;
height: 400px;
flex-direction: row;
}
#map {
flex: 3;
}
#r-result {
flex: 1;
overflow-y: auto;
}