代码
var map = new BMap.Map('map', {
enableIconClick: false,
displayOptions: {poi: false, indoor: false},
});
map.centerAndZoom(new BMap.Point(116.404, 39.915), 12);
map.enableScrollWheelZoom();
map.enableContinuousZoom();
map.addControl(
new BMap.ZoomControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT, offset: new BMap.Size(10, 80)}),
);
map.addControl(
new BMap.MapTypeControl({
anchor: BMAP_ANCHOR_BOTTOM_RIGHT,
offset: new BMap.Size(10, 10),
mapTypes: [BMAP_NORMAL_MAP, BMAP_SATELLITE_MAP, BMAP_HYBRID_MAP],
}),
);
var geocoder = new BMap.Geocoder();
var storeMarker = null;
var saved = false;
var clickMode = false;
var storePoint = null;
var searchId = 0;
var poiMarkers = [];
var poiData = {};
var activePoiCat = '餐饮';
var subwayRouteService = null;
var busRouteService = null;
var radiusCircle = null;
var storeLabel = null;
var subwayLabel = null;
var subwayPointCache = null;
var busPointCache = null;
var poiCategories = [
{name: '餐饮', color: '#f59e0b', kw: '餐饮'},
{name: '购物', color: '#ec4899', kw: '购物'},
{name: '银行', color: '#eab308', kw: '银行'},
{name: '教育', color: '#3b82f6', kw: '学校'},
{name: '医疗', color: '#ef4444', kw: '医院'},
{name: '酒店', color: '#8b5cf6', kw: '酒店'},
];
function getRadius() {
return parseInt(document.getElementById('radiusSelect').value) || 2000;
}
document.getElementById('radiusSelect').addEventListener('change', function () {
if (storePoint) placeMarker(storePoint);
});
function catIcon(color) {
var svg =
'<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22"><circle cx="11" cy="11" r="8" fill="' +
color +
'" stroke="#fff" stroke-width="2.5"/></svg>';
return new BMap.Icon('data:image/svg+xml,' + encodeURIComponent(svg), new BMap.Size(22, 22), {
anchor: new BMap.Size(11, 11),
});
}
document.getElementById('btnLocate').onclick = function () {
var geo = new BMap.Geolocation();
geo.getCurrentPosition(function (r) {
if (this.getStatus() === BMAP_STATUS_SUCCESS) {
map.flyTo(r.point, 15);
setTimeout(function () {
placeMarker(r.point);
}, 600);
}
});
};
document.getElementById('btnClickMode').onclick = function () {
clickMode = !clickMode;
this.classList.toggle('active', clickMode);
map.setDefaultCursor(clickMode ? 'crosshair' : '');
};
map.addEventListener('click', function (e) {
if (!clickMode) return;
clickMode = false;
document.getElementById('btnClickMode').classList.remove('active');
map.setDefaultCursor('');
placeMarker(e.latlng);
});
function storeIconFn() {
return null;
}
function placeMarker(point) {
searchId++;
if (storeMarker) map.removeOverlay(storeMarker);
if (storeLabel) map.removeOverlay(storeLabel);
if (subwayLabel) map.removeOverlay(subwayLabel);
clearRoutes();
clearAllPoiMarkers();
drawRadiusCircle(point);
storePoint = point;
storeMarker = new BMap.Marker(point, {enableDragging: true});
storeMarker.setAnimation(BMAP_ANIMATION_DROP);
storeMarker.addEventListener('dragend', function (e) {
placeMarker(e.point);
});
map.addOverlay(storeMarker);
reverseGeocode(point, function (addr, comp) {
fillAddressInfo(addr, comp, point);
storeLabel = new BMap.Label(addr, {position: point, offset: new BMap.Size(12, -20)});
storeLabel.setStyle({
border: 'none',
background: 'rgba(59,130,246,0.85)',
color: '#fff',
fontSize: '11px',
padding: '2px 6px',
borderRadius: '3px',
});
map.addOverlay(storeLabel);
showEmptyHint(false);
enableSave();
});
searchAllNearby(point, searchId);
}
function drawRadiusCircle(point) {
if (radiusCircle) map.removeOverlay(radiusCircle);
radiusCircle = new BMap.Circle(point, getRadius(), {
strokeColor: '#3b82f6',
strokeWeight: 1,
strokeOpacity: 0.6,
fillColor: '#3b82f6',
fillOpacity: 0.06,
});
map.addOverlay(radiusCircle);
}
function reverseGeocode(point, callback) {
geocoder.getLocation(point, function (rs) {
if (rs) callback(rs.address, rs.addressComponents);
});
}
function fillAddressInfo(addr, comp, point) {
document.getElementById('storeAddress').value = addr;
document.getElementById('province').value = comp.province || '';
document.getElementById('city').value = comp.city || '';
document.getElementById('district').value = comp.district || '';
document.getElementById('lng').value = point.lng.toFixed(6);
document.getElementById('lat').value = point.lat.toFixed(6);
}
function clearRoutes() {
if (subwayRouteService) {
subwayRouteService.clearResults();
subwayRouteService = null;
}
if (busRouteService) {
busRouteService.clearResults();
busRouteService = null;
}
}
function clearAllPoiMarkers() {
poiMarkers.forEach(function (m) {
map.removeOverlay(m);
});
poiMarkers = [];
poiData = {};
document.getElementById('poiTableBody').innerHTML =
'<tr><td colspan="3" class="poi-empty">—</td></tr>';
}
function searchAllNearby(point, sid) {
var radius = getRadius();
searchSubway(point, sid, radius);
searchBus(point, sid, radius);
searchPoiByCategory(point, sid, radius);
}
function searchSubway(point, sid, radius) {
var ls = new BMap.LocalSearch(map, {
onSearchComplete: function (r) {
if (sid !== searchId) return;
var doc = document.getElementById('nearestSubway');
if (ls.getStatus() === BMAP_STATUS_SUCCESS && r && r.getNumPois() > 0) {
var p = r.getPoi(0);
subwayPointCache = p.point;
var dist = map.getDistance(point, p.point).toFixed(0);
doc.textContent =
p.title + ' (' + (dist > 1000 ? (dist / 1000).toFixed(1) + 'km' : dist + 'm') + ')';
if (subwayLabel) map.removeOverlay(subwayLabel);
subwayLabel = new BMap.Label(p.title, {position: p.point, offset: new BMap.Size(12, -20)});
subwayLabel.setStyle({
border: 'none',
background: 'rgba(16,185,129,0.85)',
color: '#fff',
fontSize: '11px',
padding: '2px 6px',
borderRadius: '3px',
});
map.addOverlay(subwayLabel);
drawRoute(point, p.point, 'subway');
} else {
doc.textContent = '--';
subwayPointCache = null;
}
},
pageCapacity: 1,
});
ls.searchNearby('地铁站', point, radius);
}
function searchBus(point, sid, radius) {
var ls = new BMap.LocalSearch(map, {
onSearchComplete: function (r) {
if (sid !== searchId) return;
var doc = document.getElementById('nearestBus');
if (ls.getStatus() === BMAP_STATUS_SUCCESS && r && r.getNumPois() > 0) {
var p = r.getPoi(0);
busPointCache = p.point;
var dist = map.getDistance(point, p.point).toFixed(0);
doc.textContent =
p.title + ' (' + (dist > 1000 ? (dist / 1000).toFixed(1) + 'km' : dist + 'm') + ')';
drawRoute(point, p.point, 'bus');
} else {
doc.textContent = '--';
busPointCache = null;
}
},
pageCapacity: 1,
});
ls.searchNearby('公交站', point, radius);
}
document.getElementById('nearestSubway').addEventListener('click', function () {
if (subwayPointCache) map.panTo(subwayPointCache);
});
document.getElementById('nearestBus').addEventListener('click', function () {
if (busPointCache) map.panTo(busPointCache);
});
function drawRoute(start, end, type) {
var dist = map.getDistance(start, end);
if (dist < 1000) {
var walk = new BMap.WalkingRoute(map, {
renderOptions: {map: map, autoViewport: false},
onSearchComplete: function () {
if (walk.getStatus() === BMAP_STATUS_SUCCESS) {
if (type === 'subway') subwayRouteService = walk;
else busRouteService = walk;
}
},
});
walk.search(start, end);
} else {
var drive = new BMap.DrivingRoute(map, {
renderOptions: {map: map, autoViewport: false},
policy: BMAP_DRIVING_POLICY_DEFAULT,
onSearchComplete: function () {
if (drive.getStatus() === BMAP_STATUS_SUCCESS) {
if (type === 'subway') subwayRouteService = drive;
else busRouteService = drive;
}
},
});
drive.search(start, end);
}
}
function searchPoiByCategory(point, sid, radius) {
poiData = {};
var pending = poiCategories.length;
poiCategories.forEach(function (cat) {
var catName = cat.name;
var ls = new BMap.LocalSearch(map, {
onSearchComplete: function (r) {
if (sid !== searchId) return;
var items = [];
if (ls.getStatus() === BMAP_STATUS_SUCCESS && r) {
for (var i = 0; i < Math.min(r.getNumPois(), 8); i++) {
var p = r.getPoi(i);
items.push({
name: p.title,
point: p.point,
dist: map.getDistance(point, p.point),
uid: p.uid,
address: p.address || '',
});
}
}
poiData[catName] = items;
pending--;
if (pending === 0) {
addAllPoiMarkers();
renderPoiTable(activePoiCat);
fitViewToMarkers(point);
}
},
pageCapacity: 8,
});
ls.searchNearby(cat.kw, point, radius);
});
}
function fitViewToMarkers(center) {
var radius = getRadius();
var offset = radius / 111000;
var sw = new BMap.Point(center.lng - offset, center.lat - offset);
var ne = new BMap.Point(center.lng + offset, center.lat + offset);
map.setViewport([sw, ne], {margins: [60, 60, 60, 60]});
}
function addAllPoiMarkers() {
poiCategories.forEach(function (cat) {
var items = poiData[cat.name] || [];
items.forEach(function (item) {
var m = new BMap.Marker(item.point, {icon: catIcon(cat.color)});
m.addEventListener('click', function () {
var panel = new BMap.PlaceDetail(document.createElement('div'));
panel.setData(item.uid);
m.openPlaceDetail(panel);
});
map.addOverlay(m);
poiMarkers.push(m);
});
});
}
function renderPoiTable(catName) {
activePoiCat = catName;
var tbody = document.getElementById('poiTableBody');
var items = poiData[catName] || [];
var cat = poiCategories.find(function (c) {
return c.name === catName;
});
if (items.length === 0) {
tbody.innerHTML = '<tr><td colspan="3" class="poi-empty">暂无数据</td></tr>';
return;
}
var html = '';
items.forEach(function (item, idx) {
var d = item.dist > 1000 ? (item.dist / 1000).toFixed(1) + 'km' : item.dist.toFixed(0) + 'm';
html +=
'<tr data-idx="' +
idx +
'"><td class="color-dot"><span class="dot-circle" style="background:' +
cat.color +
'"></span></td><td>' +
item.name +
'</td><td>' +
d +
'</td></tr>';
});
tbody.innerHTML = html;
tbody.querySelectorAll('tr').forEach(function (tr, idx) {
tr.onclick = function () {
tbody.querySelectorAll('tr').forEach(function (r) {
r.classList.remove('active');
});
tr.classList.add('active');
map.panTo(items[idx].point);
var m = poiMarkers.find(function (pm) {
return (
pm.getPosition().lng === items[idx].point.lng &&
pm.getPosition().lat === items[idx].point.lat
);
});
if (m && items[idx].uid) {
var panel = new BMap.PlaceDetail(document.createElement('div'));
panel.setData(items[idx].uid);
m.openPlaceDetail(panel);
}
};
});
}
document.getElementById('poiTabs').addEventListener('click', function (e) {
if (!e.target.classList.contains('poi-tab')) return;
this.querySelectorAll('.poi-tab').forEach(function (t) {
t.classList.remove('active');
});
e.target.classList.add('active');
renderPoiTable(e.target.dataset.cat);
});
var localSearch = new BMap.LocalSearch(map, {
onSearchComplete: function (results) {
var container = document.getElementById('searchResults');
container.innerHTML = '';
if (!results) {
container.classList.remove('show');
return;
}
for (var i = 0; i < results.getNumPois(); i++) {
var poi = results.getPoi(i);
var item = document.createElement('div');
item.className = 'result-item';
item.innerHTML =
'<div class="name">' +
poi.title +
'</div><div class="addr">' +
(poi.address || '') +
'</div>';
(function (p) {
item.onclick = function () {
container.classList.remove('show');
document.getElementById('searchInput').value = p.title;
map.flyTo(p.point, 17);
setTimeout(function () {
placeMarker(p.point);
}, 600);
};
})(poi);
container.appendChild(item);
}
container.classList.add('show');
},
});
document.getElementById('searchInput').addEventListener('keydown', function (e) {
if (e.key === 'Enter') {
var kw = this.value.trim();
if (kw) localSearch.search(kw);
}
});
new BMap.Autocomplete({
input: 'searchInput',
location: map,
onConfirm: function (item) {
var pt = item.value.location;
if (pt) {
document.getElementById('searchResults').classList.remove('show');
map.flyTo(new BMap.Point(pt.lng, pt.lat), 17);
setTimeout(function () {
placeMarker(new BMap.Point(pt.lng, pt.lat));
}, 600);
}
},
});
function enableSave() {
var btn = document.getElementById('btnSave');
btn.disabled = false;
document.getElementById('saveHint').classList.add('hidden');
document.getElementById('statusBadge').textContent = '已选点';
document.getElementById('statusBadge').classList.remove('done');
btn.classList.remove('saved');
saved = false;
}
document.getElementById('btnSave').onclick = function () {
if (!storeMarker || saved) return;
var name = document.getElementById('storeName').value.trim();
if (!name) {
showToast('请输入门店名称');
return;
}
saved = true;
this.classList.add('saved');
this.innerHTML = '<span>OK</span> 已保存';
document.getElementById('statusBadge').textContent = '已保存';
document.getElementById('statusBadge').classList.add('done');
document.getElementById('saveHint').classList.add('hidden');
showToast('门店「' + name + '」保存成功!');
};
var toastTimer = null;
function showToast(msg) {
var el = document.getElementById('toast');
el.textContent = msg;
el.classList.add('show');
if (toastTimer) clearTimeout(toastTimer);
toastTimer = setTimeout(function () {
el.classList.remove('show');
}, 2500);
}
function showEmptyHint(show) {
document.getElementById('emptyHint').classList.toggle('hidden', !show);
}
placeMarker(new BMap.Point(116.30815, 40.05635));
预览