1. 程式人生 > >Leaflet學習筆記-載入北京地鐵線路

Leaflet學習筆記-載入北京地鐵線路

Leaflet學習筆記-載入北京地鐵線路

先上效果圖
這裡寫圖片描述

這裡寫圖片描述
本文主要由兩部分組成:

  • 獲取線路和站點json
  • Leaflet載入線路和站點GeoJson

獲取線路和站點json

高德地圖-地鐵

路線json(包含站點座標)
http://map.amap.com/service/subway?_1524027031909&srhdata=1100_drw_beijing.json
站點json(包含時間等)
http://map.amap.com/service/subway?_1524027031912&srhdata=1100_info_beijing.json

路線資料和站點資料都是以線路組織的。

利用高德地圖抓取資料

router.get('/', async(ctx, next) => {
    let p1 = getJSON_daw();
    let p2 = getJSON_info();

    const p = Promise.all([p1, p2]);

    p.then(() => {
        geojson = getGeoJson();
    }).catch(error => {
        console.log(error)
    })
});

function getGeoJson(params) {
    let geojson = initGeoJson();
_obj_daw.l.map((line, index) => { let lineObj = getLineJson(); lineObj.properties.name = line.kn; //線路名稱 lineObj.properties.lineID = line.ls; //線路ID lineObj.properties.isLoop = line.lo === "1"; //是否環線 line.st.map((station, index2) => { let coordStr = station.sl
.split(','); let coord = [coordStr[0] - 0, coordStr[1] - 0]; lineObj.geometry.coordinates.push(coord ); let pointObj = getPointJson(); pointObj.geometry.coordinates = gcj02towgs84; pointObj.properties.name = station.n; pointObj.properties.index = index2; pointObj.properties.isTransfer = station.t === "1" //是否換乘站 console.log(line.ls) let sl = _obj_info["l"].filter(p => p.ls === line.ls)[0]["st"][index2]; try { pointObj.properties.time = { "go": { "start": sl["d"][0]["ft"], "end": sl["d"][0]["lt"] }, "back": { "start": sl["d"][1]["ft"], "end": sl["d"][1]["lt"] } } } catch (error) { console.log(error) } geojson.features.push(pointObj); }) geojson.features.push(lineObj); }) fs.writeFile("geojson.json", JSON.stringify(geojson), error => console.log(error)); return geojson; } function initGeoJson() { let geojson = {}; geojson.type = "FeatureCollection"; geojson.features = []; return geojson; } function getPointJson() { let point = {} point.type = "Feature"; point.geometry = {}; point.geometry.type = "Point"; point.geometry.coordinates = []; point.properties = {}; return point; } function getLineJson() { let line = {} line.type = "Feature"; line.geometry = {}; line.geometry.type = "LineString"; line.geometry.coordinates = []; line.properties = {}; return line; }

座標糾偏

As all we know ,電子地圖座標都是經過加密處理過的,當疊加地圖後,這些偏移是不能接受的。
這裡寫圖片描述
糾偏處理用到的外掛coordtransform

            gcj02towgs84 = coordtransform.gcj02towgs84(coord[0], coord[1]);

            lineObj.geometry.coordinates.push(gcj02towgs84);

Leaflet載入線路和站點GeoJson

載入地圖容器,設定中心座標

var map = L.map("mapid", {
    attributionControl: false
}).setView([39.9, 116.36], 13);

設定底圖

var baseLayer = L.tileLayer(
    "https://api.mapbox.com/styles/v1/cumthyb/cjg59eh0x1qdp2sp51uct6dsd/tiles/256/{z}/{x}/{y}?" +
    "access_token=pk.eyJ1IjoiY3VtdGh5YiIsImEiOiJjamZ5NW9mNmEwZWlzMnFvYmJqZGtydnNpIn0.8abUPjkH8Ds6uCoXvKP02w",
);

載入Geojson

geojson = JSON.parse(xhr.responseText);
let [lines, stations] = AddGeo2map(geojson);

/**
 * 在Map上載入Geo
 * 
 * @param {any} geojson 
 */
function AddGeo2map(geojson) {
    //載入站點
    let stations = L.geoJSON(geojson, {
        filter: feature => feature.geometry.type === "Point",
        pointToLayer: function(feature, latlng) {
            // return L.circleMarker(latlng, geojsonMarkerOptions);
            return L.marker(latlng, { icon: getPointIcon(feature.properties.isTransfer) });
        }
    }).bindPopup(function(layer) {
        return getInfoForm(layer.feature.properties);
        // return layer.feature.properties.name;
    });

    //載入路線
    let lines = L.geoJSON(geojson, {
        filter: feature => feature.geometry.type === "LineString",
        style: feature => getLineStyle(feature)
    }).bindPopup(function(layer) {
        return layer.feature.properties.name;
    });
    return [lines, stations];
}

新增圖層控制元件

                var baseMaps = {
                    "baselayer": baseLayer,
                };

                var overlayMaps = {
                    "lines": lines,
                    'stations': stations
                };

                L.control.layers(baseMaps, overlayMaps).addTo(map);