Mapbox draw direction via two markers - javascript

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

Related

Map crashes when I zoom to an extent that is too far east

I've got a map with a button that zooms to the extent of a feature. It works fine most of the time but when the extent is too far east the entire map dissapears.
This is what I've got in javascript:
function initMap() {
var view = new ol.View({
center: endpoint,
zoom: 4,
maxZoom: 16,
});
map = new ol.Map({
target: 'map',
layers:[],
view: view
});
map.addControl(zoomToExtentControl);
};
zoomToExtentControl = new ol.control.ZoomToExtent({
extent: [-1013450.0281739295, 3594671.9021477713, 6578887.117336057, 10110775.689402476],
className: 'custom-zoom-extent',
label: 'Z'
});
and later in another function:
let xMinMax = ol.proj.fromLonLat([xMin, xMax]);
let yMinMax = ol.proj.fromLonLat([yMin, yMax]);
let padding = 1.06;
zoomToExtentControl.extent = [(xMinMax[0] * padding), (yMinMax[0] * (padding-0.02)), (xMinMax[1] * padding), (yMinMax[1] * padding)];
Why does the map crash when the extent is in the east but work fine when its not? How can I fix this?
I don't understand the xMinMax/yMinMax calculation, ol.proj.fromLonLat input is a coordinate as longitude and latitude, i.e. an array with longitude as 1st and latitude as 2nd element. It seems you are using two longitudes or two latitudes (I read two x and two y).

How to show driving distance on openlayers map?

I am using OpenLayers map in UWP desktop app.But my opelayers Map is not showing driving distance(Route) from one point to another point. i can able to show map and markers on it like location markers on map but not able to show route between source and destination.
Any help Would be appreciated.
Here is my code:
var lat = mylatitutde;
var long = mylongitutde;
var zoom = 8;
var vectorLayer = new OpenLayers.Layer.Vector("Overlay");
var fromProjection = new OpenLayers.Projection("EPSG:4326");
// Transform from WGS 1984
var toProjection = new OpenLayers.Projection("EPSG:900913");
// to Spherical Mercator Projection
map = new OpenLayers.Map("Map");
map.addControl(new OpenLayers.Control.PanZoomBar());
var mapnik = new OpenLayers.Layer.OSM();
map.addLayer(mapnik);
var markers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(markers);
var position = new OpenLayers.LonLat(long, lat).transform(fromProjection, toProjection);
var marker = new OpenLayers.Marker(position);
var feature = new OpenLayers.`enter code here`Feature(markers, position);
vectorLayer.addFeatures(feature);
markers.addMarker(new OpenLayers.Marker(position));
map.setCenter(position, zoom);
map.addLayer(vectorLayer);
Is there any solution to show route between two locations in Open Layers map??
Calculating the optimal path to drive from A to B is not a task OpenLayers is designed for. It is merely there to display a map and map-related-things on it.
Of course, OpenLayers can display a route, but you somehow first have to calculate it. There are good examples on the OL website. Here is one showing a precalculated route as PolyLine, or one using IGC data.

Measuring distance between two points using google api

I'm trying to measure the distance between a marker and a point that has been searched for by postcode. The idea is to make markers appear within a certain radius. as far as I can tell I've done it right but clearly not.
The current code for the function looks like this:
function setup_map(latitude, longitude) {
var _position = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: 14,
center: _position
}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
#foreach (var i in ViewData.Model)
{
<text>
var markerPos = {lat: #i.Lat, lng:#i.Long}
var distance = google.maps.geometry.spherical.computeDistanceBetween(markerPos, _position);
var marker = new google.maps.Marker
({
position: new google.maps.LatLng (markerPos),
map: map,
title: "" + (#i.id),
});
</text>
}
}
This function reloads the map and all the markers on it. At the minute I'm not too concerned with loading the markers within the radius. I just want to load them all.
When you click the search button, the map loads to the postcode entered but doesn't load any markers. If I remove the "var distance" line, it still goes to the postcode and loads all of the markers. So by process of elimination, there must be something wrong with this line but I have no idea what.

Destination coordinates in leaflet routing

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

Leaflet OSM: Center mapview on polygon

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);

Categories