How to include Leaflet plugin Leaflet.Locate

Leaflet Plugin Leaflet.Locate: A useful control to geolocate the user with many options.

This works on devices with GPS only, you need to enable access to GPS for this app.

When using the maps, content is loaded from third-party servers. If you agree to this, a cookie will be set and this notice will be hidden. If not, no maps will be displayed.


Preparation

Download css and js from Github and put in upload directory (e.g. /wp-content/uploads/leaflet-plugins/locatecontrol).

Code

Use e.g. WPCode and configure this as a PHP snippet in Frontend only.

<?php
if (!function_exists('leafext_locatecontrol_function')) {
	function leafext_enqueue_locatecontrol () {
		wp_enqueue_script('locatecontrol',
		'/wp-content/uploads/leaflet-plugins/locatecontrol/L.Control.Locate.min.js',
		array('wp_leaflet_map'), null);
		wp_enqueue_style('locatecontrol',
		'/wp-content/uploads/leaflet-plugins/locatecontrol/L.Control.Locate.min.css',
		array('leaflet_stylesheet'), null);
	}
	function leafext_locatecontrol_script(){
		$text = '
		<script>
		window.WPLeafletMapPlugin = window.WPLeafletMapPlugin || [];
		window.WPLeafletMapPlugin.push(function () {
			var map = window.WPLeafletMapPlugin.getCurrentMap();
			L.control.locate().addTo(map);
		});
		</script>';
		return "\n".$text."\n";
	}
	function leafext_locatecontrol_function( $atts ){
		leafext_enqueue_locatecontrol ();
		return leafext_locatecontrol_script();
	}
	add_shortcode('locatecontrol', 'leafext_locatecontrol_function' );
}

Shortcode

Then use a shortcode like:

[leaflet-map]
[locatecontrol]

Where am I ?

Nofollow!