IncrementP MP WORLD+

Contact Us
TOP > Digital Map Introduction > Make a web map with Leaflet using MapFan API
2021.10.15

Make a web map with Leaflet using MapFan API

To display a movable map on a web page that reacts to mouse clicks and taps, a JavaScript map library is required to be included on that page.

MapFan API, a kit for developing web systems provides a JavaScript library for making it possible to display maps of the same design as MapFan on web sites and do searching and routing on a map.

In this article, we will show you how to make MapFan API map displayed on web using Leaflet.js, a well-known open-source JavaScript library.

What is Leaflet.js?

Leaflet.js is one of the most well-known open-source JavaScript map libraries. It has the following features and is used in many commercial services.

  • Support of a broad range of browsers including mobile versions
  • Simple interface for easier development
  • Provide wide array of plugins and high extensibility
  • License: BSD-2-Clause

We present a procedure step by step for displaying a map retrieved from the MapFan API using Leaflet.

Step 1: Prepare a HTML file
Step 2: Implement authentication
Step 3: Implement a map display

Note:  it is out of Increment P technical support scope to answer inquiries about how to use Leaflet.

[Step 1] Prepare a HTML file

On the first step, the css and JavaScript codes are written in a HTML file to complete the map display in one single HTML file.

First, prepare base HTML code as shown below and prepare an area to display a map using the div tag and assign an ID. The css is set up in such a way that a map is displayed in full-screen mode.

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title>MapFan API Leafletサンプル</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script>
    <style type="text/css">
        html, body {
            height: 100%;
            width: 100%;
            margin: 0;
            padding: 0;
        }
        #map {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <div id='map'></div>
    <script>
        // ここに処理を実装
    </script>
</body>
</html>

Leaflet css and js files are loaded from the CDN shown on the Leaflet official page.
https://leafletjs.com/download.html#using-a-hosted-version-of-leaflet

[Step 2] Implement authentication

Next step is to implement authentication processing.

Call “authentication API: auth” to retrieve an access key.

Parameters for “authentication API” are as shown below.

 https://api-map.mapfan.com/v1/auth?
appid  Authentication ID           Authentication IDIPC issues one for each client.
Free plan up to 5,000 free PVs is available.
See this page for more details.              
date date and time as of when the API is used Specify a date and time in “yyyyMMddhhmmss”.
callback Name of a callback function used in JSONP If not specified, a response is returned in JSON.

Source code is as shown below. Processing results of the authentication API are received in JSONP.

var authId = '【認証ID】'
var authUrl = 'https://api-auth.mapfan.com/v1/auth?';

var date = new Date();
var now = zeroPadding(date.getFullYear(), 4) + zeroPadding(date.getMonth() + 1, 2) + zeroPadding(date.getDate(), 2) + zeroPadding(date.getHours(), 2) + zeroPadding(date.getMinutes(), 2) + zeroPadding(date.getSeconds(), 2);

var script = document.createElement('script');
script.src = authUrl + 'appid=' + authId + '&date=' + now + '&callback=authCallback';
document.head.appendChild(script);

// ゼロパディング
function zeroPadding(number, digit) {
    return (Array(digit).join('0') + number).slice(-digit);
}

// 認証APIのコールバック関数
function authCallback(result) {
    if(result.status === 'success') {
        // ここに地図表示処理を実装
    }
}

In the example above, an authentication ID is hardcoded in the source code. For use in a public service, however, consider a system configuration that keeps an authentication ID from leaking and sends to the page only an access key retrieved by calling the authentication API on the server side.

[Step 3] Implement a map display

The last step is to implement map display processing.
By specifying the “map image retrieval API: map” URL in Leaflet, Leaflet dynamically requests and displays a map for the area displayed on the screen.
Key parameters for the “map image retrieval API” are as follows.

 https://api-map.mapfan.com/v1/map?
 key  Access Key           Access key is obtained from Authentication API.               
 tilematrix Tile matrix Tile matrix is specified in “EPSG code” and “Scale”.
EPSG code is  “EPSG:3857” or “EPSG:900913” and Scale is expressed in “{z}”. 
 tilecol  WMTS tile number
(longitude direction)
 Specified in “{x}” format
 tilerow  WMTS tile number
(latitude direction)
 Specified in “{y}” format

An example code is contained in the “callback function for the authentication API” presented in the authentication process above.

// 認証APIのコールバック
function authCallback(result) {
    if(result.status === 'success') {
        var mapUrl = 'https://api-map.mapfan.com/v1/map?';

        // LeafletのMapクラスに、地図を表示する領域のdivタグのidを指定
        // 初期表示位置・スケールは、東京駅・スケール17に設定
        var map = L.map('map').setView([35.68116552628331, 139.76719388020982], 17);

        // 地図画像取得APIを、LeafletのTileLayerクラスのURLに指定
        L.tileLayer(mapUrl + 'key=' + result.key + '&tilematrix=EPSG:3857:{z}&tilecol={x}&tilerow={y}&', {
            maxZoom: 21,
            minZoom: 6,
            attribution: '&copy INCREMENT P CORPORATION <a href="https://api-auth-pre.mapfan.com/terms/mfapi_terms.pdf">利用規約</a>'
        }).addTo(map);

        // スケーラーを表示
        L.control.scale({ maxWidth: 200, position: 'bottomleft', imperial: false }).addTo(map);
    }
}

This is a display result.

Conclusion

All the source code presented so far is as follows.

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title>MapFan API Leafletサンプル</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script>
    <style type="text/css">
        html, body {
            height: 100%;
            width: 100%;
            margin: 0;
            padding: 0;
        }
        #map {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <div id='map'></div>
    <script>
        var authId = '【認証ID】';
        var authUrl = 'https://api-auth.mapfan.com/v1/auth?';

        var date = new Date();
        var now = zeroPadding(date.getFullYear(), 4) + zeroPadding(date.getMonth() + 1, 2) + zeroPadding(date.getDate(), 2) + zeroPadding(date.getHours(), 2) + zeroPadding(date.getMinutes(), 2) + zeroPadding(date.getSeconds(), 2);

        var script = document.createElement('script');
        script.src = authUrl + 'appid=' + authId + '&date=' + now + '&callback=authCallback';
        document.head.appendChild(script);

        // ゼロパディング
        function zeroPadding(number, digit) {
            return (Array(digit).join('0') + number).slice(-digit);
        }

        // 認証API コールバック
        function authCallback(result) {
            if(result.status === 'success') {
                var mapUrl = 'https://api-map.mapfan.com/v1/map?';

                // LeafletのMapクラスに、地図を表示する領域のdivタグのidを指定
                // 初期表示位置・スケールは、東京駅・スケール17に設定
                var map = L.map('map').setView([35.68116552628331, 139.76719388020982], 17);

                // 地図画像取得APIを、LeafletのTileLayerクラスのURLに指定
                L.tileLayer(mapUrl + 'key=' + result.key + '&tilematrix=EPSG:3857:{z}&tilecol={x}&tilerow={y}&', {
                    maxZoom: 21,
                    minZoom: 6,
                    attribution: '&copy INCREMENT P CORPORATION <a href="https://api-auth-pre.mapfan.com/terms/mfapi_terms.pdf">利用規約</a>'
                }).addTo(map);

                // スケーラーを表示
                L.control.scale({ maxWidth: 200, position: 'bottomleft', imperial: false }).addTo(map);
            }
        }
    </script>
</body>
</html>

Now you have prepared a 60-line page with a movable map embedded. By replacing [authentication ID] at line 24 with an ID issued for you, you can check if the page functions correctly on your browser.

 

This article presented a method of map display as a simple function of map. MapFan API also provides APIs that have the following features:

Retrieve static unscrollable map images
Retrieve latitude and longitude from addresses and spot names (geocoding)
Retrieve addresses from latitude and longitude (reverse geocoding)
Retrieve vehicle/pedestrian routing information
Conversion of Japanese Geodetic Datum versus JGD2000

The “map image retrieval API” also provides parameters for controlling objects display on a map and changing the map design.

We will come back to you with those usage of parameters on another occasion.

Click here to contact us for inquiry of map database and services.

Related Service

Related Articles