这是一份OpenLayers使用高德地图并绘制一些线代码,这高德来源好像不太正规建议自己去开发者平台逛逛。代码都有注释我就不过多介绍了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>OpenLayers Map</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@v10.0.0/ol.css">
<script src="https://cdn.jsdelivr.net/npm/ol@v10.0.0/dist/ol.js"></script>
<style>
html,
body {
margin: 0;
height: 100%;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
button {
/* 定位按钮位置 */
position: absolute;
z-index: 10;
}
</style>
</head>
<body>
<div id="map"></div>
<button onclick="initDrawLines()">Draw Lines</button>
<script>
//高德地图引用
const gaode = new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'https://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}'
})
});
//OpenLayers使用核心方法
const map = new ol.Map({
target: 'map',
layers: [
gaode,
],
view: new ol.View({
center: ol.proj.fromLonLat([116.3974, 39.9087]),
zoom: 15,
projection: 'EPSG:3857'
})
});
// 计算平行线的功能
function offsetLine(line, distance, side, lineCoordinates) {
const coords = line.getCoordinates();
const coord = coords[0];
const nextCoord = coords[1];
const dx = nextCoord[0] - coord[0];
const dy = nextCoord[1] - coord[1];
const length = Math.sqrt(dx * dx + dy * dy);
const offsetX = (dy / length) * distance;
const offsetY = -(dx / length) * distance;
const offsetCoords = coords.map((coord, index) => {
console.log('Line coordinates:', offsetX, offsetY, ol.proj.toLonLat([coord[0] + offsetX, coord[1] + offsetY]),);
if (side === 'left') {
return [coord[0] + offsetX, coord[1] + offsetY];
} else {
return [coord[0] - offsetX, coord[1] - offsetY];
}
});
console.log('Line coordinates:', offsetCoords, "start", ol.proj.toLonLat(offsetCoords[0]), "end", ol.proj.toLonLat(offsetCoords[1]));
lineCoordinates.push({ start: ol.proj.toLonLat(offsetCoords[0]), end: ol.proj.toLonLat(offsetCoords[1]) });
return new ol.geom.LineString(offsetCoords);
}
// 绘制线条的函数
function drawLines(lonA, latA, lonB, latB, numLines, distanceBetweenLines) {
const pointA = ol.proj.fromLonLat([lonA, latA]);
const pointB = ol.proj.fromLonLat([lonB, latB]);
const mainLine = new ol.geom.LineString([pointA, pointB]);
const vectorSource = new ol.source.Vector();
let lineCoordinates = [];
// 循环创建平行线
for (let i = 1; i <= numLines; i++) {
const offset = i * distanceBetweenLines;
// 偏移左侧线
const leftLine = offsetLine(mainLine, offset, 'left', lineCoordinates);
const leftFeature = new ol.Feature(leftLine);
vectorSource.addFeature(leftFeature);
// 偏移右侧线
const rightLine = offsetLine(mainLine, offset, 'right', lineCoordinates);
const rightFeature = new ol.Feature(rightLine);
vectorSource.addFeature(rightFeature);
}
// 主线
const mainFeature = new ol.Feature(mainLine);
vectorSource.addFeature(mainFeature);
// 创建矢量图层
const vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
})
})
});
map.setLayers([gaode, vectorLayer])
// 返回线条的坐标
return lineCoordinates;
}
// 初始化并调用 drawLines 函数
function initDrawLines() {
const latA = 39.9087;
const lonA = 116.3974;
const latB = 40;
const lonB = 110;
const numLines = 6;
const distanceBetweenLines = 10;
const coordinates = drawLines(lonA, latA, lonB, latB, numLines, distanceBetweenLines);
console.log('Line coordinates:', coordinates);
}
</script>
</body>
</html>
Android
class MainActivity : AppCompatActivity() {
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val webView = findViewById<WebView>(R.id.webView)
val astart = findViewById<EditText>(R.id.astart)
val aend = findViewById<EditText>(R.id.aend)
val bstart = findViewById<EditText>(R.id.bstart)
val bend = findViewById<EditText>(R.id.bend)
val sum = findViewById<EditText>(R.id.sum)
val spacing = findViewById<EditText>(R.id.spacing)
val quer = findViewById<Button>(R.id.quer)
quer.setOnClickListener {
webView.evaluateJavascript(
"javascript:drawLines(${astart.text}, ${aend.text}, ${bstart.text}, ${bend.text}, ${sum.text}, ${spacing.text})"
){
Log.e("WebAppInterface", "CSV 文件已保存到: ${convertJsonToCsv(it)}")
}
}
val webSettings = webView.settings
webSettings.javaScriptEnabled = true
// 加载HTML文件
webView.loadUrl("file:///android_asset/index.html")
}
fun convertJsonToCsv(jsonString: String?): String {
val csvData = StringBuilder()
// CSV Header
csvData.append("start_latitude,start_longitude,end_latitude,end_longitude\n")
try {
// 解析JSON数组
val jsonArray = JSONArray(jsonString)
for (i in 0 until jsonArray.length()) {
val obj = jsonArray.getJSONObject(i)
val startArray = obj.getJSONArray("start")
val endArray = obj.getJSONArray("end")
// 获取start和end的纬度和经度
val startLatitude = startArray.getDouble(1)
val startLongitude = startArray.getDouble(0)
val endLatitude = endArray.getDouble(1)
val endLongitude = endArray.getDouble(0)
// 生成CSV行数据
csvData.append(startLatitude).append(",")
.append(startLongitude).append(",")
.append(endLatitude).append(",")
.append(endLongitude).append("\n")
}
} catch (e: Exception) {
e.printStackTrace()
}
return csvData.toString()
}
}