最近公司要做一个地图点选的功能,根据百度api做了一个
核心代码主要就是这一个页面,里面都是调用的百度api功能做的。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Map</title>
<style type="text/css">
html {
height: 100%
}
body {
height: 100%;
margin: 0px;
padding: 0px
}
#container {
height: 80%
}
.divlist {
border-bottom: 1px dashed #CCCCCC;
float: left;
margin: 2px 10px 0px 5px;
padding: 0px 0px 2px 5px;
width: 97%;
font-size: smaller;
}
.divLeft {
float: left;
}
.divRight {
float: right;
}
</style>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=Uf9eG5K56zOeTzaeRZugtLychewE45mw">
</script>
</head>
<body>
<div style="margin: 2px 0 4px 2px; font-size: smaller;">
<span>
地址:<input id="suggestId" type="text" style="width: 300px;">
<input type="hidden" id="lat"><input type="hidden" id="lng">
</span>
<span style="float: right; padding: 1px 12px 1px 0px">
<input type="button" id="save" onclick="confirmResult()" class="btn" value="保存">
</span>
</div>
<div id="container"></div>
<script type="text/javascript">
function trim(str) {
return null == str ? "" : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
}
// 地图数据对象,调用时返回就是此对象
var mapObj = {
longitude: "",
latitude: "",
province: "",
city: "",
district: "",
street: "",
streetNumber: "",
address: "",
addressDetail: ""
}
// 创建地图实例
var map = new BMap.Map("container");
// 参数初始化
initParams();
if ("" != mapObj.longitude && "" != mapObj.latitude) {
var point = new BMap.Point(mapObj.longitude, mapObj.latitude);
map.centerAndZoom(point, 13);
addMarker(mapObj.longitude, mapObj.latitude);
} else if ("" != mapObj.province) {
var localSearch = new BMap.LocalSearch(map);//创建搜索
var keyword = mapObj.province;
if ("" != mapObj.city) {
keyword += mapObj.city;
}
if ("" != mapObj.district) {
keyword += mapObj.district;
}
if ("" != mapObj.address) {
keyword += mapObj.address;
}
localSearch.setSearchCompleteCallback(function (searchResult) {
var poi = searchResult.getPoi(0);
if(null != poi){
//获取经度和纬度,将结果显示在文本框中
map.centerAndZoom(poi.point, 13);
addMarker(poi.point.lng, poi.point.lat);
}else{
autoPositionByBrowse();
}
});
localSearch.search(keyword);
} else {
autoPositionByBrowse();
}
// 创建点坐标
// var point = new BMap.Point(116.404, 39.915);
// 初始化地图,设置中心点坐标和地图级别
// map.centerAndZoom(point, 13);
map.enableScrollWheelZoom();
map.enableInertialDragging();
map.enableContinuousZoom();
var size = new BMap.Size(10, 20);
map.setDefaultCursor("default");//鼠标样式
map.addControl(new BMap.CityListControl({
anchor: BMAP_ANCHOR_TOP_LEFT,
offset: size,
}));
// 添加带有定位的导航控件
var navigationControl = new BMap.NavigationControl({
// 靠左上角位置
anchor: BMAP_ANCHOR_TOP_RIGHT,
// LARGE类型
type: BMAP_NAVIGATION_CONTROL_LARGE,
// 启用显示定位
enableGeolocation: false
});
map.addControl(navigationControl);
map.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_LEFT})); // 右下比例尺
map.addControl(new BMap.OverviewMapControl({isOpen: true, anchor: BMAP_ANCHOR_BOTTOM_RIGHT})); //小比例窗口
//input 自动填充
var ac = new BMap.Autocomplete( //建立一个自动完成的对象
{
"input": "suggestId",
"location": map
});
ac.addEventListener("onconfirm", function (e) { //鼠标点击下拉列表后的事件
//business String 商户名
var _value = e.item.value;
var addr = _value.province + _value.city + _value.district + _value.street + _value.streetNumber + _value.business;
// console.log(addr);
setPositionByAddress(addr);
});
function showInfo(e) {
//var point = new BMap.Point(e.point.lng,e.point.lat);
addMarker(e.point.lng, e.point.lat);
}
map.addEventListener("click", showInfo);
// 根据经纬度标点
function addMarker(lng, lat) {
map.clearOverlays();
// 使用自定义图标
// var myIcon = new BMap.Icon("front/images/icon/marker_1.png", new BMap.Size(18, 52));
// myIcon.setImageSize(new BMap.Size(16, 26));
// marker = new BMap.Marker(new BMap.Point(lng, lat), {icon: myIcon}); // 创建标注
marker = new BMap.Marker(new BMap.Point(lng, lat)); // 创建标注
marker.enableDragging();
marker.addEventListener("dragend", function (e) {
showCurrentPositions(e.point);
});
map.addOverlay(marker);
var pi = new BMap.Point(lng, lat);
showCurrentPositions(pi);
setPositionValByPoint(lng, lat);
}
// 根据位置设置经纬度
function setPositionByAddress(addr) {
// 创建地址解析器实例
var geoc = new BMap.Geocoder();
// 将地址解析结果显示在地图上,并调整地图视野
geoc.getPoint(addr, function (point) {
if (point) {
map.centerAndZoom(point, 13);
// console.log("setPositionByAddress:" + point.lng + " , " + point.lat)
addMarker(point.lng, point.lat);
} else {
alert("您选择地址没有解析到结果!");
}
});
}
// 根据经纬度设置对象的位置值
function setPositionValByPoint(lng, lat) {
// 创建地址解析器实例
var geoc = new BMap.Geocoder();
var point = new BMap.Point(lng, lat);
geoc.getLocation(point, function (rs) {
var addComp = rs.addressComponents;
// console.log(rs.address);
mapObj.longitude = lng;
mapObj.latitude = lat;
mapObj.province = addComp.province;
mapObj.city = addComp.city;
mapObj.district = addComp.district;
mapObj.street = addComp.street;
mapObj.streetNumber = addComp.streetNumber;
mapObj.address = rs.address;
});
}
// 显示当前点的位置集合
function showCurrentPositions(point) {
var local = new BMap.LocalSearch(point, {
onSearchComplete: function (results) {
document.getElementById("div-positions").innerHTML = "";
if (local.getStatus() == BMAP_STATUS_SUCCESS) {
if (Array.isArray(results)) {
results.forEach(function (item) {
setContent(item);
});
} else {
setContent(results);
}
}
}
});
var myGeo = new BMap.Geocoder();
myGeo.getLocation(point, function (result) {
console.log(result);
if (result) {
var keys = new Array();
var i = 0;
result.surroundingPois.forEach(function (e) {
keys[i++] = e.title;
})
console.log(keys)
local.search(keys);
}
});
}
function setContent(localResult) {
var content = document.getElementById("div-positions").innerHTML;
var size = localResult.getCurrentNumPois();
size = size > 3 ? 3 : size; // 最多一个关键字只显示3条记录
for (var i = 0; i < size; i++) {
var title = localResult.getPoi(i).title;
var address = localResult.getPoi(i).address;
var points = localResult.getPoi(i).point;
content += "<div class='divlist'><div class='divLeft'>";
content += address + title + "</div><div class='divRight'><input type='button'";
content += " pointLng='" + points.lng + "' pointLat='" + points.lat + "' addr='" + trim(address) + "'";
content += " title='" + title + "' onclick='selectItem(this)'";
content += " value='选取'></div></div>";
}
document.getElementById("div-positions").innerHTML = content;
}
function selectItem(dom) {
mapObj.addressDetail = dom.getAttribute("addr")+dom.getAttribute("title");
mapObj.longitude = dom.getAttribute("pointLng");
mapObj.latitude = dom.getAttribute("pointLat");
setPositionValByPoint(mapObj.longitude, mapObj.latitude);
confirmResult();
}
function confirmResult() {
filterPCS();
window.parent.baseMapObj.setValue(mapObj);
window.parent.baseMapObj.call();
var index = parent.layer.getFrameIndex(window.name);
parent.layer.close(index);
}
// 过滤详细地址中的省市区
function filterPCS() {
var detail = mapObj.addressDetail;
detail = detail.replace(mapObj.province, "");
detail = detail.replace(mapObj.city, "");
detail = detail.replace(mapObj.district, "");
mapObj.addressDetail = detail;
}
// 初始化窗口传的参数
function initParams(){
var paramobj = window.parent.baseMapObj.mobj;
if(null == paramobj){
return;
}
if(null != paramobj.longitude && "" != paramobj.longitude){
mapObj.longitude = paramobj.longitude
}
if(null != paramobj.latitude && "" != paramobj.latitude){
mapObj.latitude = paramobj.latitude
}
if(null != paramobj.province && "" != paramobj.province){
mapObj.province = paramobj.province
}
if(null != paramobj.city && "" != paramobj.city){
mapObj.city = paramobj.city
}
if(null != paramobj.district && "" != paramobj.district){
mapObj.district = paramobj.district
}
if(null != paramobj.address && "" != paramobj.address){
mapObj.address = paramobj.address
}
}
// 根据浏览器定位
function autoPositionByBrowse() {
var geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(function (r) {
if (this.getStatus() == BMAP_STATUS_SUCCESS) {
// 初始化地图,设置中心点坐标和地图级别
map.centerAndZoom(r.point, 13);
addMarker(r.point.lng, r.point.lat);
}
else {
console.log('failed' + this.getStatus());
}
}, {enableHighAccuracy: true})
}
</script>
<div id="div-positions">
</div>
</body>
</html>
调用的时候先把调用部分封装到一个公共的js,添加代码如下,这里的弹窗用的layui 的弹窗,如果你的代码不是layui 可以用其他的替换
/**
* 简单弹窗
* @param url
* @param width 单位 px
* @param height 单位 px
* @returns
*/
function layerOpen(url, width, height) {
layer.open({
type: 2
, title: false //不显示标题栏
, closeBtn: true
, area: [width, height]
, id: 'LAY_layuipro' //设定一个id,防止重复弹出
, moveType: 1 //拖拽模式,0或者1
, content: url
});
}
var baseMapObj = {};
/**
* 调用打开地图
* @param mapObj 参数对象字段包含
* {
longitude: "", 经度
latitude: "", 纬度
provice: "", 省名
city: "", 市名
district: "", 区名
address: "" 详细地址
}
* @param callback 回调函数
* @param _width 地图宽 默认 800px
* @param _height 地图高 默认 500px
*/
function openMap(mapObj, callback, _width = '800px', _height='500px') {
var url = "openMap.html";
layerOpen(url, _width, _height);
baseMapObj = new BaseMapObj(mapObj, callback);
}
function BaseMapObj(mapObj, callback) {
this.mobj = mapObj;
this.callback = callback;
}
BaseMapObj.prototype.call = function () {
if (this.callback) {
this.callback(this.mobj);
}
}
BaseMapObj.prototype.setValue = function (obj) {
this.mobj = obj;
}
页面调用时的代码
function openBaiduMap() {
var data = {
longitude: "113.861818",
latitude: "22.613461",
province: "四川省",
city: "绵阳市",
district: "盐亭县",
address: "十里坡1119号"
};
openMap(null,function(obj){
console.log("openBaiduMap========")
console.log(obj)
})
}
实施s s