Showing your geolocation with OpenStreetMap
Step 1 - Coding the view openstreetmap.php
The view openstreetmap.php
must be installed into the INSTALL_DIR/applications/default/app/view/
folder.
- The button with
id='location-button'
when clicked, zooms into the user's current location. - The
<DIV>
element withid='map'
is the container that displays the map. - The jQuery event handler on the ZnetDK for Mobile
afterviewdisplay
events loads the map when the view is displayed for the first time. - The OpenStreetMap standard tile layer is loaded from the
https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png
url. - The Leaflet API
locate()
method, based on the HTML5 JS Geolocation API, allows you to retrieve the user's GPS coordinates, provided that the user accepts to be geolocated via the functionality of the internet browser. - On geolocation success (see
onLocationFound()
function), a marker is displayed on the map and a circle is drawn to indicate how accurately the user has been located. - In order to retrieve the postal address from the user's GPS coordinates (reverse geocoding), the Nominatim web service is called through the jQuery
ajax()
function. - Finally, a popup attached to the user's location marker displays their GPS coordinates in latitude and longitude as well as the corresponding postal address.
View openstreetmap.php
<div class="w3-stretch w3-margin-bottom w3-margin-top">
<button id="location-button" class="w3-button w3-theme-action"><i class="fa fa-map-marker"></i> See my location</button>
</div>
<div id='map' class="w3-stretch"></div>
<style>
#map { height: 65vh; }
#zdk-side-nav-menu { z-index: 1004; } /* To display the side navigation menu over the map */
</style>
<script>
console.log('<openstreetmap> view - Inline JS Code');
var map = null, locationMarker = null, locationCircle = null;
$('body').on('afterviewdisplay', function (event, viewId) { /* Once the view is displayed ... */
if (viewId === 'openstreetmap' && map === null) {
map = L.map('map', {zoomControl: false}).fitWorld();
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
map.setZoom(2);
map.on('locationfound', onLocationFound);
map.on('locationerror', onLocationError);
}
});
$('#location-button').on('click', function(){ /* On button click... */
if (map !== null) {
map.locate({setView: true, maxZoom: 17});
$(this).prop('disabled', true);
}
});
function onLocationFound(e) { /* When the user's location is found... */
var radius = e.accuracy / 2,
popupMsg = 'You are within <b>' + Math.round(radius) + ' meters</b> from this point.<br>'
+ 'Position: lat=<b>' + e.latlng.lat + '</b>, long=<b>' + e.latlng.lng + '</b>.<br>';
locationMarker = L.marker(e.latlng).addTo(map).bindPopup(popupMsg);
locationCircle = L.circle(e.latlng, radius).addTo(map);
// Reverse geocoding to get postal address
reverseGeocode(e.latlng.lat, e.latlng.lng, function(postalAddress){
popupMsg += 'Address: <b>' + postalAddress + '</b>';
locationMarker.unbindPopup().bindPopup(popupMsg).openPopup();
});
}
function onLocationError(e) { /* In case of location error */
console.error('Location error: ' + e.message);
}
function reverseGeocode(latitude, longitude, callback) { /* Reverse geocoding */
$.ajax({
type: 'POST',
url: 'https://nominatim.openstreetmap.org/reverse?format=geojson&lat='
+ latitude + '&lon=' + longitude,
dataType: 'json',
success: function (response) {
callback(response.features[0].properties.display_name);
}
}).fail(function(jqXHR, textStatus) {
console.error('Request failed: ' + textStatus);
});
}
</script>
HTM5
JS
Step 2 - Loading the CSS and JS Leaflet libraries
The Leaflet CSS and JavaScript libraries are automatically loaded by specifying into the config.php
of the Web App, the matching url on the CDN hosting (see Settings | App extra CSS and JS libraries).
The config.php
script is located into the INSTALL_DIR/applications/default/app/
folder.
The two lines below can be inserted anywhere in the config.php
script.
Script config.php
define('CFG_APP_JS', 'https://unpkg.com/leaflet@1.7.1/dist/leaflet.js');
define('CFG_APPLICATION_CSS', 'https://unpkg.com/leaflet@1.7.1/dist/leaflet.css');
PHP
Step 3 - Adding an "OpenStreetMap" item to the navigation menu
Finally, to give users access to the openstreetmap.php
view, a menu item definition is added into the menu.php
script of the Web App (see Get Started | New menu items for more information).
The menu.php
script is located into the INSTALL_DIR/applications/default/app/
folder.
Script menu.php
static public function initAppMenuItems() {
// ... Here, some menu items...
\MenuManager::addMenuItem(NULL, 'openstreetmap', 'OpenStreetMap', 'fa-globe');
// ... Here, other menu items...
}
PHP