高德座標打點(點為正常的WGS84地球座標系,常見於 GPS 裝置,Google 地圖等國際標準的座標體系)偏移,調整偏移量

张甜瓜發表於2024-06-03

建立一個js檔案工具

// WGS84 to GCJ-02 converter
// 高德轉地球座標
// coordinateUtils.js

const PI = 3.1415926535897932384626;
const a = 6378245.0; // a: WGS84 大地座標系的長半軸
const ee = 0.00669342162296594323; // ee: WGS84 橢球的偏心率平方

// WGS84 to GCJ-02 converter
export function wgs84ToGcj02(lng, lat) {
if (outOfChina(lng, lat)) {
return [lng, lat];
}

let dLat = transformLat(lng - 105.0, lat - 35.0);
let dLng = transformLng(lng - 105.0, lat - 35.0);
const radLat = lat / 180.0 * PI;
let magic = Math.sin(radLat);
magic = 1 - ee * magic * magic;
const sqrtMagic = Math.sqrt(magic);
dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * PI);
dLng = (dLng * 180.0) / (a / sqrtMagic * Math.cos(radLat) * PI);
const mgLat = lat + dLat;
const mgLng = lng + dLng;
return [mgLng, mgLat];
}

function transformLat(lng, lat) {
let ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
return ret;
}

function transformLng(lng, lat) {
let ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
return ret;
}

function outOfChina(lng, lat) {
// 緯度 3.86~53.55, 經度 73.66~135.05
return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55);
}

import { wgs84ToGcj02 } from '../../utils/coordinateUtils';
在元件中先引入後打點使用封裝方法,主要是這個( let [lng, lat] = wgs84ToGcj02(parseFloat(item.lng), parseFloat(item.lat));)
function addMarker(stations) {
// console.log("stations",stations);
map.value.clearMap();
stations.forEach((item) => {
if (item.lng === null || item.lat === null) {
return;
}
let [lng, lat] = wgs84ToGcj02(parseFloat(item.lng), parseFloat(item.lat));
console.log("lng",lng);
let icon = new AMap_P.value.Icon({
size: new AMap_P.value.Size(30, 30),
image: MapIconPic,
imageOffset: new AMap_P.value.Pixel(0, 0),
imageSize: new AMap_P.value.Size(30, 30),
});
// 建立 LngLat 物件
let position = new AMap_P.value.LngLat(lng, lat);
// console.log("position",position);
let marker = new AMap_P.value.Marker({
icon: icon,
position: [position.lng, position.lat],
zIndex: 1000,
title: [item.lng, item.lat],
label: {
content: item.stationId,
direction: 'bottom',
style: { 'background-color': 'red' },
},
});
markers.value.push(marker);
map.value.add(markers.value);

相關文章