NAV Navbar

Table of Contents

GompWebServiceJsClient

Map8 (web service) API 的 client 端 SDK (for Javascript).

透過本 SDK,您可以很方便地於開發前端瀏覽器網頁 Javascript 程式時,直接使用本 SDK library 的 API,輕輕鬆鬆就能呼叫 台灣圖霸 | Map8 Platform 的 API 並取回結果供您做進一步的處理。

Parameters

Examples

// 一個最基本的範例 (此處以 [Map8 Place Autocomplete API](https://www.map8.zone/map8-api-docs/#api-place-autocomplete-api) 為例)

// 當然,HTML 內,請先如下引用本 SDK 之 .js 檔案 :
// <script type="text/javascript" src="https://api.map8.zone/maps/js/gomp-web-service-js-client.min.js?key=您的key"></script>

var gompWebServiceJsClient = new GompWebServiceJsClient({key: gomp.accessToken});
...
var config = {};
...
config = extend(config, {query: searchInput});
var request = gompWebServiceJsClient.autocomplete(config, function(responseText) {
    if (responseText instanceof Error) {      // Error
        console.log("Error");
    }
    else {                                    // Success
        var resp = JSON.parse(responseText);
        console.log(resp);

        if (resp.predictions) {    // autocomplete...
            console.log(resp.predictions);
        }
    }
});
// 一個較複雜 (但也比較接近通常的使用情況) 的範例
var gompWebServiceJsClient = new GompWebServiceJsClient({key: gomp.accessToken});
...
var config = {};
...
config = extend(config, {query: searchInput});
var request = gompWebServiceJsClient.autocomplete(config, function(responseText) {
    if (responseText instanceof Error) {      // Error
        console.log("Error");
    }
    else {                                    // Success
        var resp = JSON.parse(responseText);
        console.log(resp);

        // 此處示範將得到的 API response 透過 data transformation 手法以變形為適用於自身 application 的資料結構
        // 1. 先定義 data transformation function
        var transformMap8ApiResponseGeoRecordToFeatures = function(map8ApiRespGeoRecord) {
            var feature = {
                type : "Feature",
                properties : map8ApiRespGeoRecord,
                geometry : {
                    coordinates: [
                        map8ApiRespGeoRecord.geometry.location.lng,
                        map8ApiRespGeoRecord.geometry.location.lat
                    ],
                    type : "Point"
                },
                place_type: []
            };
            var featureTitle;
            var featureDescription;
            feature.place_type.push(map8ApiRespGeoRecord.type);
            if (map8ApiRespGeoRecord.type == '地點') {
                featureTitle = map8ApiRespGeoRecord.name + ' (' + map8ApiRespGeoRecord.city + map8ApiRespGeoRecord.town + ')';
                feature.place_type.push(map8ApiRespGeoRecord.cat);
            }
            else if (map8ApiRespGeoRecord.type == '地址') {
                featureTitle = map8ApiRespGeoRecord.city + map8ApiRespGeoRecord.town + map8ApiRespGeoRecord.name;
            }
            else if (map8ApiRespGeoRecord.type == '道路') {
                featureTitle = map8ApiRespGeoRecord.city + map8ApiRespGeoRecord.town + map8ApiRespGeoRecord.name;
            }

            // Extend properties
            feature.properties.name = map8ApiRespGeoRecord.name;
            feature.place_name = featureTitle;
            feature.center = feature.geometry.coordinates;

            return feature;
        });
        var matchingFeatures = [];
        if (resp.status == "OK") {
            var candidatesList;

            // 2. 依據所呼叫 API 的回傳結構,指派給通用的變數 (`candidatesList`)
            if (resp.predictions) {    // autocomplete...
                candidatesList = resp.predictions;
            } 
            if (resp.results) {
                candidatesList = resp.results;
            }

            // 3. 最後即可直接以此通用變數開始做 data transformation
            if (candidatesList) {
                candidatesList.forEach(function(candidate) {
                    //console.log(candidate);   // Deubg
                    var feature = transformMap8ApiResponseGeoRecordToFeatures(candidate);                
                    matchingFeatures.push(feature);
                });
            }
        }

        // 4. 將 data transformation 完的結果指派回 res.features (假設 event handler 之預期為這樣的結構),然後發出 `results` 事件供相關 listener / subscriber 去處理
        res.features = matchingFeatures;
        this._eventEmitter.emit('results', res);
    }
});

findplace

Parameters

placedetails

Parameters

autocomplete

Parameters

textsearch

Parameters

nearbysearch

Parameters

directions

Parameters

geocode

地址定位 (geocoding, 將 地址 / 門牌 轉為地理座標 經緯度),與反地址定位 (reverse geocoding, 將地理座標 經緯度 轉為 地址 / 門牌)。

Parameters

nearestRoads

對道路進行反定址 (也就是由輸入之地理座標轉為道路),並獲取道路屬性。

Parameters

nearbyamenity

Parameters

nearbyAmenityGeoJson

呼叫 nearbyamenity function / method,並將結果轉為 GeoJSON 結構回傳。

var map8Apikey = 'YOUR_KEY_HERE';

gomp.accessToken = map8Apikey;
var map = new gomp.Map({
    container: 'map', // 地圖容器 ID
    style: 'https://api.map8.zone/styles/go-life-maps-tw-style-std/style.json', // 地圖樣式檔案位置
    maxBounds: [[105, 15], [138.45858, 33.4]], // 台灣地圖區域
    center: [121.54885, 25.03625], // 初始中心座標,格式為 [lng, lat]
    zoom: 16, // 初始 ZOOM LEVEL; [0-20, 0 為最小 (遠), 20 ;最大 (近)]
    minZoom: 6, // 限制地圖可縮放之最小等級, 可省略, [0-19.99]
    maxZoom: 19.99, // 限制地圖可縮放之最大等級, 可省略 [0-19.99]
    pitch: 50, // 攝影機仰角, 可省略, [0-60]
    bearing: 0, // 地圖角度, 可省略, [-180 ~ 180; 0 為正北朝上, 180 為正南朝上]
    attributionControl: false
}).addControl(new gomp.AttributionControl({
    compact: false
}).addControl(new gomp.NavigationControl());

var gompWebServiceJsClient = new GompWebServiceJsClient({
    key: map8Apikey
});

gompWebServiceJsClient.nearbyAmenityGeoJson(
    {
        query: [lat, lng],         // 中心點座標 (緯度, 經度)
        nearbyAmenityRadius: 1,    // 1 KM
    }, 
    function(nearbyDataGeoJson) {
        console.log(nearbyDataGeoJson);      // 轉出之 GeoJSON 資料結構如下
    }
);
{
    type: 'FeatureCollection', 
    features: [{
        type: 'Feature',
        geometry: {...},
        properties: {...}
    }, 
    ..., {
        type: 'Feature',
        geometry: {...},
        properties: {...}
   }]
}

Parameters

nearbynimby

Parameters

nearbyNimbyGeoJson

呼叫 nearbynimby function / method,並將結果轉為 GeoJSON 結構回傳。

gompWebServiceJsClient.nearbyNimbyGeoJson(
    {
        query: [lat, lng],         // 中心點座標 (緯度, 經度)
        nearbyNimbyRadius: 1,      // 1 KM
    }, 
    function(nearbyDataGeoJson) {
        console.log(nearbyDataGeoJson);      // 轉出之 GeoJSON 資料結構如下
    }
);
{
    type: 'FeatureCollection', 
    features: [{
        type: 'Feature',
        geometry: {...},
        properties: {...}
    }, 
    ..., {
        type: 'Feature',
        geometry: {...},
        properties: {...}
   }]
}

Parameters

schooldistricts

查詢所給定的地理經緯度座標之所屬學區 (國中、國小)。

var map8Apikey = 'YOUR_KEY_HERE';

var gompWebServiceJsClient = new GompWebServiceJsClient({
    key: map8Apikey
});

gompWebServiceJsClient.schooldistricts(
    {
        location: [25.037893, 121.548771],         // 中心點座標 (緯度, 經度)
        kind: "國小",                              // 篩選 `國小`
    }, 
    function(map8SchoolDistrictsRespText) {
        console.log("Map8 Premium [Housing] School Districts API response text : ", map8SchoolDistrictsRespText);

        map8SchoolDistrictsObj = JSON.parse(map8SchoolDistrictsRespText);

        if (map8SchoolDistrictsObj.status === "OK") {
            map8SchoolDistrictsObj.results.forEach(function(resultObj) {
                console.log("Result object : ", resultObj);
            });
        }
    }
);
Map8 Premium [Housing] School Districts API response text :  {"html_attribution":["台灣圖霸","研鼎智能","PAPAGO!"],"results":[{"city":"台北市","town":"大安區","name":"仁愛國小","kind":"國小"}],"status":"OK"}

Result object :  {city: "台北市", town: "大安區", name: "仁愛國小", kind: "國小"}

Parameters

metersToPixelsAtZoomLevel20

基於給定之中心點 (緯度座標),將所給地理長度 (單位為公尺),換算出圖面座標的長度 (單位為 pixels)

// Circle
map.addLayer({
    id: "circle",
    type: "circle",
    source: {
        type: "geojson",
        data: {
            type: "FeatureCollection",
            features: [{
                type: "Feature",
                geometry: {
                    type: "Point",
                    coordinates: [lng, lat]
                }
            }]
        }
    },
    paint: {
        "circle-radius": {
            stops: [
                [0, 0],
                [20, gompWebServiceJsClient.metersToPixelsAtZoomLevel20(radius, lat)]
            ],
            base: 2
         },
         "circle-color": colorIndex["blue"],
         "circle-opacity": 0.2
    }
});
map.addLayer({
    id: "circle-text",
    type: "symbol",
    source: {
        type: "geojson",
        data: {
            type: "FeatureCollection",
            features: [{
                type: "Feature",
                geometry: {
                    type: "Point",
                    coordinates: [lng, lat]
                }
            }]
        }
    },
    layout: {
        'text-allow-overlap': true,
        'text-field': '半徑 500 公尺範圍',
        'text-font': ["Open Sans Regular"],
        'text-offset': [0, 1],
        'text-size': 15
    },
    paint: {
        'text-color': colorIndex["blue"],
        'text-halo-color': '#fff',
        'text-halo-width': 2
    }
});

Parameters

Returns number 所換算得之圖面座標長度 (單位為 pixels)

getDistanceFromLatLngInKm

求出兩地理座標之間的距離。

var distInKm = gompWebServiceJsClient.getDistanceFromLatLngInKm(25.037893, 121.548771, 24.854564, 121.822903);

Parameters

Returns number 距離 (單位為公里)

distancematrix

Parameters

trip

Parameters

snapToRoads

Parameters