代码
var map = new BMap.Map('map');
map.centerAndZoom(new BMap.Point(116.404, 39.915), 12);
map.enableScrollWheelZoom();
var overlays = [];
var convertor = new BMap.Convertor();
var currentMode = 'points';
var lastPoints = [];
// 坐标系对应颜色
var coordColors = {5: '#3385ff', 3: '#ff6633', 1: '#33cc66'};
// 打点/画线/画面按钮,点击直接上图
document.querySelectorAll('.actions button[data-mode]').forEach(function (btn) {
btn.onclick = function () {
currentMode = this.dataset.mode;
executeDraw();
};
});
function executeDraw() {
var text = document.getElementById('input').value.trim();
if (!text) return;
var coordType = parseInt(document.getElementById('coordType').value);
var statusEl = document.getElementById('status');
statusEl.textContent = '';
statusEl.className = 'status';
// 尝试解析 GeoJSON
var geojson = tryParseGeoJSON(text);
if (geojson) {
var points = extractGeoJSONPoints(geojson);
if (!points.length) {
statusEl.textContent = 'GeoJSON 中无有效坐标';
statusEl.className = 'status error';
return;
}
convertAndDraw(points, coordType, geojson);
return;
}
// 解析坐标文本
// 将所有分隔符统一拆分为数字序列,每两个为一组 lng,lat
var tokens = text.split(/[,;\|\s\t\n]+/).filter(function (t) {
return t.trim();
});
var parsed = [];
if (tokens.length < 2 || tokens.length % 2 !== 0) {
statusEl.textContent = '坐标数量不正确,请确保每组包含经度和纬度';
statusEl.className = 'status error';
return;
}
for (var i = 0; i < tokens.length; i += 2) {
var lng = parseFloat(tokens[i]),
lat = parseFloat(tokens[i + 1]);
if (isNaN(lng) || isNaN(lat)) {
statusEl.textContent = '第 ' + (i / 2 + 1) + ' 组坐标格式错误';
statusEl.className = 'status error';
return;
}
parsed.push({lng: lng, lat: lat});
}
if (!parsed.length) return;
convertAndDraw(parsed, coordType, null);
}
function convertAndDraw(parsed, coordType, geojson) {
var statusEl = document.getElementById('status');
var points = parsed.map(function (p) {
return new BMap.Point(p.lng, p.lat);
});
if (coordType === 5) {
// 已经是 BD09,直接绘制
draw(points, parsed, geojson);
} else {
// 需要坐标转换,分批处理(API 限制每次最多10个点)
statusEl.textContent = '坐标转换中...';
batchConvert(points, coordType, 5, function (converted) {
if (!converted) {
statusEl.textContent = '坐标转换失败';
statusEl.className = 'status error';
return;
}
draw(converted, parsed, geojson);
});
}
}
function batchConvert(points, from, to, callback) {
var batchSize = 100;
var result = [];
var batches = [];
for (var i = 0; i < points.length; i += batchSize) {
batches.push(points.slice(i, i + batchSize));
}
var done = 0;
batches.forEach(function (batch, idx) {
convertor.translate(batch, from, to, function (res) {
if (res.status === 0) {
for (var j = 0; j < res.points.length; j++) {
result[idx * batchSize + j] = res.points[j];
}
}
if (++done === batches.length) {
callback(result.length === points.length ? result : null);
}
});
});
}
function draw(points, parsed, geojson) {
var statusEl = document.getElementById('status');
var keepPrev = document.getElementById('keepPrev').checked;
// 是否保留上次结果
if (!keepPrev) {
overlays.forEach(function (o) {
map.removeOverlay(o);
});
overlays = [];
}
lastPoints = points;
var color = coordColors[document.getElementById('coordType').value] || '#3385ff';
if (geojson) {
drawGeoJSON(geojson, points, parsed, color);
} else if (currentMode === 'points') {
points.forEach(function (pt) {
var marker = new BMap.Marker(pt, {
icon: new BMap.Icon(
'data:image/svg+xml,' +
encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="32"><path d="M12 0C5.4 0 0 5.4 0 12c0 9 12 20 12 20s12-11 12-20C24 5.4 18.6 0 12 0z" fill="' +
color +
'"/><circle cx="12" cy="12" r="4" fill="#fff"/></svg>',
),
new BMap.Size(24, 32),
),
});
map.addOverlay(marker);
overlays.push(marker);
});
} else if (currentMode === 'polyline') {
var polyline = new BMap.Polyline(points, {
strokeColor: color,
strokeWeight: 3,
strokeOpacity: 0.8,
});
map.addOverlay(polyline);
overlays.push(polyline);
} else {
var polygon = new BMap.Polygon(points, {
strokeColor: color,
strokeWeight: 2,
fillColor: color,
fillOpacity: 0.2,
});
map.addOverlay(polygon);
overlays.push(polygon);
}
map.setViewport(points, {margins: [50, 50, 50, 380]});
statusEl.className = 'status';
statusEl.innerHTML =
'<span>已绘制 ' +
points.length +
' 个坐标点</span><a onclick="copyXY()">复制坐标</a><a onclick="copyGeoJSON()">复制GeoJSON</a>';
}
function drawGeoJSON(geojson, convertedPoints, parsed, color) {
var features =
geojson.type === 'FeatureCollection'
? geojson.features
: geojson.type === 'Feature'
? [geojson]
: [{type: 'Feature', geometry: geojson}];
var ptIdx = 0;
features.forEach(function (feature) {
var geom = feature.geometry;
if (!geom) return;
var props = feature.properties || {};
if (geom.type === 'Point') {
var marker = new BMap.Marker(convertedPoints[ptIdx]);
if (props.name || props.title) {
var label = new BMap.Label(props.name || props.title, {offset: new BMap.Size(20, -10)});
label.setStyle({
border: '1px solid #ccc',
padding: '2px 6px',
fontSize: '12px',
background: '#fff',
borderRadius: '3px',
});
marker.setLabel(label);
}
map.addOverlay(marker);
overlays.push(marker);
ptIdx++;
} else if (geom.type === 'MultiPoint') {
geom.coordinates.forEach(function () {
var marker = new BMap.Marker(convertedPoints[ptIdx++]);
map.addOverlay(marker);
overlays.push(marker);
});
} else if (geom.type === 'LineString') {
var pts = geom.coordinates.map(function () {
return convertedPoints[ptIdx++];
});
var line = new BMap.Polyline(pts, {strokeColor: color, strokeWeight: 3, strokeOpacity: 0.8});
map.addOverlay(line);
overlays.push(line);
} else if (geom.type === 'MultiLineString') {
geom.coordinates.forEach(function (coords) {
var pts = coords.map(function () {
return convertedPoints[ptIdx++];
});
var line = new BMap.Polyline(pts, {
strokeColor: color,
strokeWeight: 3,
strokeOpacity: 0.8,
});
map.addOverlay(line);
overlays.push(line);
});
} else if (geom.type === 'Polygon') {
geom.coordinates.forEach(function (ring) {
var pts = ring.map(function () {
return convertedPoints[ptIdx++];
});
var polygon = new BMap.Polygon(pts, {
strokeColor: color,
strokeWeight: 2,
fillColor: color,
fillOpacity: 0.2,
});
map.addOverlay(polygon);
overlays.push(polygon);
});
} else if (geom.type === 'MultiPolygon') {
geom.coordinates.forEach(function (poly) {
poly.forEach(function (ring) {
var pts = ring.map(function () {
return convertedPoints[ptIdx++];
});
var polygon = new BMap.Polygon(pts, {
strokeColor: color,
strokeWeight: 2,
fillColor: color,
fillOpacity: 0.2,
});
map.addOverlay(polygon);
overlays.push(polygon);
});
});
}
});
}
function tryParseGeoJSON(text) {
try {
var obj = JSON.parse(text);
if (
obj &&
(obj.type === 'FeatureCollection' ||
obj.type === 'Feature' ||
obj.type === 'Point' ||
obj.type === 'MultiPoint' ||
obj.type === 'LineString' ||
obj.type === 'MultiLineString' ||
obj.type === 'Polygon' ||
obj.type === 'MultiPolygon')
) {
return obj;
}
} catch (e) {}
return null;
}
function extractGeoJSONPoints(geojson) {
var points = [];
var features =
geojson.type === 'FeatureCollection'
? geojson.features
: geojson.type === 'Feature'
? [geojson]
: [{type: 'Feature', geometry: geojson}];
features.forEach(function (feature) {
var geom = feature.geometry;
if (!geom) return;
if (geom.type === 'Point') {
points.push({lng: geom.coordinates[0], lat: geom.coordinates[1]});
} else if (geom.type === 'MultiPoint') {
geom.coordinates.forEach(function (c) {
points.push({lng: c[0], lat: c[1]});
});
} else if (geom.type === 'LineString') {
geom.coordinates.forEach(function (c) {
points.push({lng: c[0], lat: c[1]});
});
} else if (geom.type === 'MultiLineString') {
geom.coordinates.forEach(function (line) {
line.forEach(function (c) {
points.push({lng: c[0], lat: c[1]});
});
});
} else if (geom.type === 'Polygon') {
geom.coordinates.forEach(function (ring) {
ring.forEach(function (c) {
points.push({lng: c[0], lat: c[1]});
});
});
} else if (geom.type === 'MultiPolygon') {
geom.coordinates.forEach(function (poly) {
poly.forEach(function (ring) {
ring.forEach(function (c) {
points.push({lng: c[0], lat: c[1]});
});
});
});
}
});
return points;
}
function copyXY() {
var text = lastPoints
.map(function (p) {
return p.lng + ',' + p.lat;
})
.join('\n');
navigator.clipboard.writeText(text);
document.getElementById('status').querySelector('span').textContent = '已复制坐标';
}
function copyGeoJSON() {
var geojson;
if (currentMode === 'points') {
geojson = {
type: 'FeatureCollection',
features: lastPoints.map(function (p) {
return {
type: 'Feature',
geometry: {type: 'Point', coordinates: [p.lng, p.lat]},
properties: {},
};
}),
};
} else if (currentMode === 'polyline') {
geojson = {
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: lastPoints.map(function (p) {
return [p.lng, p.lat];
}),
},
properties: {},
};
} else {
var coords = lastPoints.map(function (p) {
return [p.lng, p.lat];
});
coords.push(coords[0]);
geojson = {
type: 'Feature',
geometry: {type: 'Polygon', coordinates: [coords]},
properties: {},
};
}
navigator.clipboard.writeText(JSON.stringify(geojson, null, 2));
document.getElementById('status').querySelector('span').textContent = '已复制 GeoJSON';
}
预览