I am using nominatim for leaflet routing. The routing works perfectly as i want-a user can input from and destination location in search box and the map shows the route between the two points as in the picture below.
But I want to get the coordinates of the destination location. Is there any way i can do this ? Below is code sample how i have added map to my page.
var map = L.map('map').setView([60.4500, 22.2667], 8);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map)
L.Routing.control({
waypoints: [
//L.latLng(60.323935,22.344035)
],
geocoder: L.Control.Geocoder.nominatim()
}).addTo(map);
Look at the RoutingResultEvent. It will be called each time a route has been successfully calculated. The event the handler will receive contains the waypoints used for the route.
So basically
var x = L.Routing.control({
// YOUR STUFF
geocoder: L.Control.Geocoder.nominatim()
}).addTo(map);
x.on("routesfound", function(e) {
var waypoints = e.waypoints || [];
var destination = waypoints[waypoints.length - 1]; // there you have the destination point between your hands
});
you can use:
routeControl.on("routesfound", function(e) {
coordinates=e.routes[0].coordinates;
destination=coordinates[coordinates.length-1];
});
there you have the coordinates, the waypoints are not the same as the coordinates, what you are looking for is for the coordinates of the route found, and not for the waypoints that you have asked for, then you can take the coordinates.lenght-1 and there you will have what you wanted
Related
I'm trying to get the waypoints from a route (leaflet routing machine) as latitude and longitude so I can write these out to a database. However when I call getwaypoints I also get additional data about the route that I don't want.
How do i get just the lat/long as JSON so I can write it out to a db?
var map = L.map('map').setView([-27.54, 152.9], 10);
L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all//{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap © CartoDB',
maxZoom: 19
}).addTo(map);
var routeControl = L.Routing.control({waypoints: [
L.latLng(-27.38851, 153.11606),
L.latLng(-27.47577, 153.01693)
]}).addTo(map);
var routeArray = new Array();
routeArray = routeControl.getWaypoints();
alert (JSON.stringify(routeArray));
Output
[{"options":{"allowUTurn":false},"latLng":{"lat":-27.38851,"lng":153.11606},"_initHooksCalled":true},{"options":{"allowUTurn":false},"latLng":{"lat":-27.47577,"lng":153.01693},"_initHooksCalled":true}]
Please see example fiddle: http://jsfiddle.net/drcccx91/8/
Solution was to not convert to JSON
alert (routeArray[0].latLng.lng);
Well, I am using leaflet api and then I found a very nice supporting plugin called leaflet routing machine for showing address from A to B with nice route.
However, leaflet routing machine working fine with passing of latlng but not working with passing address so can anyone tell how it can work as I know property information on following link:
So routing waypoint have property called name but don;t know how to use it to provide address a and address B
Here is a code which shows new Zealand Auckland city....and trying to pass address but doesn't work
< script >
var mymap = L.map('mapid', {
center: [-36.85625, 174.76141],
zoom: 13
});
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.yourkey', {
attribution: 'Log Sample',
id: 'mapbox.streets'
}).addTo(mymap);
//L.Control.geocoder().addTo(mymap);
L.Routing.control({
waypoints: [
//L.latLng(-36.87178, 174.753),
//L.latLng(-36.84514, 174.76493)
L.name("12 Morning Star place, Auckland"),
L.name("198 Dominion road, Mount Roskill, Auckland")
],
routeWhileDragging: false
}).addTo(mymap); < /script>
As far as remember you can pass L.Routing.Waypoint object to waypoints as well.
So, your code would look like:
....
var geocoder = L.Control.Geocoder.nominatim()
L.Routing.control({
geocoder: geocoder,
waypoints: [
//L.latLng(-36.87178, 174.753),
//L.latLng(-36.84514, 174.76493)
L.Routing.waypoint(null,"12 Morning Star place, Auckland"),
L.Routing.waypoint(null,"198 Dominion road, Mount Roskill, Auckland")
],
routeWhileDragging: false,
}).addTo(mymap);
But this again doesn't geocode it. Instead just populates waypoints textboxes. You still need to hit enter (or trigger it by js) on each of the boxes to run geocoder.
Another option would be manually grabbing data from geocoder and create L.Routing.Waypoint or L.LatLng object before setting waypoints
geocoder.geocode('Montreal', function(a, b) {
// depending on geocoder results may be either in a or b
console.log(a);
// choose the best result here. probably the first one in array
// create waypoint object
var wpt = L.Routing.waypoint(L.latLng(lat, lng), name)
waypoints.push(wpt);
})
...
// setting waypoints
routingControl.setWaypoints(waypoints);
Update to cover question in comments
The custom markers with popup could be added via L.Routing.Plan. Your L.Routing.control object could be initialized like so:
var geocoder = L.Control.Geocoder.nominatim(),
waypoints = [], // can be populated later
routeControl = L.Routing.control({
plan: L.Routing.plan(waypoints, {
createMarker: function(i, wp) {
return L.marker(wp.latLng, {
draggable: true
}).bindPopup("Some data for popup");
},
geocoder: geocoder,
routeWhileDragging: false,
})
}).addTo(map);
How can i draw route direction from start to finish if I have coordinates of this two points?
Now my code looks like this and it just gave me 2 static markers on map
var map = L.mapbox.map('map', 'mapbox.streets', {
zoomControl: false
}).setView([start.lat, start.lng], 12);
map.attributionControl.setPosition('bottomleft');
var directions = L.mapbox.directions({
profile: 'mapbox.walking'
});
var directionsLayer = L.mapbox.directions.layer(directions).addTo(map);
L.marker([start.lat, start.lng], {}).addTo(map);
L.marker([finish.lat, finish.lng], {}).addTo(map);
If I understand correctly, you wish to use Mapbox's direction and routing layer to get the walking route between the two points and display it. To do so you need to set the origin and destination points and call the query() function of direction. You also need to add a routes control to the map. The revised code is as follows.
// example origin and destination
var start = {lat: 22.3077423, lng: 114.2287582};
var finish = {lat: 22.3131334, lng: 114.2205973};
var map = L.mapbox.map('map', 'mapbox.streets', {
zoomControl: false }).setView([start.lat, start.lng], 14);
map.attributionControl.setPosition('bottomleft');
var directions = L.mapbox.directions({
profile: 'mapbox.walking'
});
// Set the origin and destination for the direction and call the routing service
directions.setOrigin(L.latLng(start.lat, start.lng));
directions.setDestination(L.latLng(finish.lat, finish.lng));
directions.query();
var directionsLayer = L.mapbox.directions.layer(directions).addTo(map);
var directionsRoutesControl = L.mapbox.directions.routesControl('routes', directions)
.addTo(map);
You may not need to add the origin / destination markers yourself, as origin / destination markers would be displayed as part of the directions control.
You'll need a polyline for that. Leaflet's (Mapbox is an extended version of Leaflet) class L.Polyline is what you need:
Reference: http://leafletjs.com/reference.html#polyline
Code:
var polyline = new L.Polyline([
[start.lat, start.lng],
[finish.lat, finish.lng]
]).addTo(map);
Example on Plunker: http://plnkr.co/edit/2XSeS1?p=preview
I'm trying to get the waypoints from a route (leaflet routing machine) as latitude and longitude so I can write these out to a database. However when I call getwaypoints I also get additional data about the route that I don't want.
How do i get just the lat/long as JSON so I can write it out to a db?
var map = L.map('map').setView([-27.54, 152.9], 10);
L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all//{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap © CartoDB',
maxZoom: 19
}).addTo(map);
var routeControl = L.Routing.control({waypoints: [
L.latLng(-27.38851, 153.11606),
L.latLng(-27.47577, 153.01693)
]}).addTo(map);
var routeArray = new Array();
routeArray = routeControl.getWaypoints();
alert (JSON.stringify(routeArray));
Output
[{"options":{"allowUTurn":false},"latLng":{"lat":-27.38851,"lng":153.11606},"_initHooksCalled":true},{"options":{"allowUTurn":false},"latLng":{"lat":-27.47577,"lng":153.01693},"_initHooksCalled":true}]
Please see example fiddle: http://jsfiddle.net/drcccx91/8/
Solution was to not convert to JSON
alert (routeArray[0].latLng.lng);
I want generate a html file including Leaflet library to show an OpenStreetMap view with a polygon. The polygon on the map should be centered. To do so i followed this discussion, but its still unclear to me, how to center an arbitrary polygon and autozoom it. Autozoom means to me, that the polygon is completly in the visible map excerpt and fills it.
As example this would be the desired result:
This is my code so far:
var map;
var ajaxRequest;
var plotlist;
var plotlayers=[];
function initmap() {
// set up the map
map = new L.Map('map');
/* --- Replace for different URL for OSM tiles */
var url_base ='URL_TO_MY_OPENSTREETMAPS_SERVER';
var latitude = 50.2222;
var longtitude = 3.322343;
var poly = L.polygon([
[50.2222, 3.322343],
[50.2322, 3.323353],
[...]
]);
// create the tile layer with correct attribution
var osmUrl=url_base+'{z}/{x}/{y}.png';
var osmAttrib='Map data ɠOpenStreetMap contributors';
var osm = new L.TileLayer(osmUrl, {minZoom: 4, maxZoom: 20, attribution: osmAttrib});
// start the map at specific point
map.setView(new L.LatLng(latitude, longtitude),15);
map.addLayer(osm);
poly.addTo(map);
}
Especially it would be great, if there are "onboard" methods of Leaflet that i can use. How to calculate the center of a polygon is clear to (e.g. here) but maybe there are already implemnented methods i can use.
Solution:
// start the map at specific point
// map.setView(new L.LatLng(latitude, longtitude),15); <- Remove this line
map.addLayer(osm);
poly.addTo(map);
map.fitBounds(poly.getBounds()); // <- Add this line
Not exactly centering, but if you want the map to be fitted to the polygon:
map.fitBounds(poly.getBounds());
(doc).
To center more than one polygon is good to know that .fitBounds also accepts an array as argument, so you could do this:
const poly = [polygonA,polygonB,polygonC];
const bounds = poly.map(p=>p.getBounds());
mymap.fitBounds(bounds);