How to connect geolocation with Open Street maps?
tips: Get open street maps api and input the latitude and longitude that have been obtained right.
The following is an example of the program code
<!-- Open Street Map Api -->
<link
href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"
rel="stylesheet"
/>
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"></script>
<div id="sodik-osmap-canvas"></div>
<script>
// navigator.geolocation
var iframeOpenStreet = document.getElementById("sodik-osmap-canvas"),
getLocation = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition);
// The Geolocation.getCurrentPosition() method is used to get the current position of the device.
} else {
// Section showing error or incompatible browser.
}
},
getPosition = (position) => {
iframeOpenStreet.style = "height:300px;";
var map = L.map(iframeOpenStreet);
// Add OSM tile layer to the Leaflet map.
L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {
attribution:
'© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
subdomains: ["a", "b", "c"],
}).addTo(map);
// Target GPS coordinates.
var target = L.latLng(
position.coords.latitude,
position.coords.longitude
);
// Set map center to target with zoom 14.
map.setView(target, 14);
// Place a marker on the same location.
L.marker(target).addTo(map);
};
getLocation();
// [open-source] : location:github.com/tamddk/library/tree/main/getGeoLocationWithOSMAPS
</script>