如何將OpenStreetMap放到網頁中使用

JLin
5 min readAug 23, 2019

--

一開始想說使用Google map來使用,後來發現才load一次就說要登記付費資訊,

後來找到有人寫好的js

也可以參考這個人的

可以直接引用後直接使用,更方便且快速

直接用這個做成一個.html就可以看到地圖了

<!DOCTYPE html>
<html>
<head>
<title>Quick Start - Leaflet</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js" integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og==" crossorigin=""></script>
</head>
<body>
<div id="mapid" style="width: 600px; height: 400px;"></div>
<script>
var mymap = L.map('mapid').setView([25.0077081,121.4661477], 18);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
id: 'mapbox.streets'
}).addTo(mymap);

var marker = L.marker([25.0077327,121.4664855]).addTo(mymap);
</script>
</body>
</html>

一開始new一個map

var mymap = L.map('mapid').setView([25.0077081,121.4661477], 18);

然後如果想要加上一個marker

var marker = L.marker([25.0077327,121.4664855]).addTo(mymap);

如果想要點選後跳出視窗

var marker1 = L.marker([25.0079017,121.4651737]).addTo(mymap);
marker1.bindPopup("<strong>綜合大樓</strong><br>這是第一個");

另外可以看到網站有相當多的範例

其他再補上

--

--

JLin

台中 / JAVA / Android /Kotlin / Kotlin Native 對於Kotlin衍生的JVM等技術 Compose for web / desktop / Ktor Server,生成式AI (Gemini/OpenAI)各式應用, 都有小興趣