使用Mapbox打开从阵列中预先收费的路线地图



我正在尝试使用Mapbox(因为现在地图是付费的(,我的服务基本上是:

  1. 用户创建一条进入地图的路线***服务获取坐标并创建
  2. 创建的路由保存在数据库中(js或php,我不知道如何做更好(
  3. 关闭窗口后,当用户返回网站时,路线(步骤1(将在那里

我的实际问题是显示路线,我无法理解文档。。。所以,我使用一个数组来完成每一次点击(这是有效的(,但如何完成下一步(4(?

以下代码:

<script>
var truckLocation = [-49.3766505877158, -20.80796326493855];
var warehouseLocation = [-49.3766505877158, -20.80796326493855];
var lastQueryTime = 0;
var lastAtRestaurant = 0;
var keepTrack = [];
var currentSchedule = [];
var currentRoute = null;
var pointHopper = {};
var pause = true;
var speedFactor = 50;
var capturaCoordenada = ['lat,long'];
var exibeCoordenada ="";


// Add your access token
mapboxgl.accessToken = 'personal token';
// Initialize a map

var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/light-v10', // stylesheet location
center: truckLocation, // starting position
zoom: 15 // starting zoom
});
var warehouse = turf.featureCollection([turf.point(warehouseLocation)]);
map.on('load', function() {
var marker = document.createElement('div');
marker.classList = 'onibus';

// Create a new marker
var truckMarker = new mapboxgl.Marker(truckMarker)
.setLngLat(truckLocation)
.addTo(map);
});
// Create a circle layer
map.on('load', function() {
map.addSource("points", {
"type": "geojson",
"data": warehouseLocation
})
map.addLayer({
id: 'warehouse',
type: 'circle',
source: {
data: warehouse,
type: 'geojson'
},
paint: {
'circle-radius': 20,
'circle-color': 'white',
'circle-stroke-color': '#4287f5',
'circle-stroke-width': 3
}
});
// Create a symbol layer on top of circle layer
map.addLayer({
id: 'warehouse-symbol',
type: 'geojs',
source: {
data: warehouse,
type: 'geojson'
},
layout: {
'icon-image': 'grocery-15',
'icon-size': 1
},
paint: {
'text-color': '#3887be'
}
});

// Create an empty GeoJSON feature collection for drop-off locations
var dropoffs = turf.featureCollection([]);
map.addLayer({
id: 'dropoffs-symbol',
type: 'symbol',
source: {
data: dropoffs,
type: 'geojson'
},
layout: {
'icon-allow-overlap': true,
'icon-ignore-placement': true,
'icon-image': 'marker-15',
}
});
// Listen for a click on the map
map.on('click', function(e) {
// When the map is clicked, add a new drop-off point
// and update the `dropoffs-symbol` layer
newDropoff(map.unproject(e.point));
updateDropoffs(dropoffs);
});
function newDropoff(coords) {
// Store the clicked point as a new GeoJSON feature with
// two properties: `orderTime` and `key`
var pt = turf.point(
[coords.lng, coords.lat],
{
orderTime: Date.now(),
key: Math.random()
}
);
dropoffs.features.push(pt);
}
function updateDropoffs(geojson) {
map.getSource('dropoffs-symbol')
.setData(geojson);
}
// Create an empty GeoJSON feature collection, which will be used as the data source for the route before users add any new data
var nothing = turf.featureCollection([]);
map.addSource('route', {
type: 'geojson',
data: nothing
});
map.addLayer({
id: 'routeline-active',
type: 'line',
source: 'route',
layout: {
'line-join': 'round',
'line-cap': 'round'
},
paint: {
'line-color': '#3887be',
'line-width': [
"interpolate",
["linear"],
["zoom"],
12, 3,
22, 12
]
}
}, 'waterway-label');
// Here you'll specify all the parameters necessary for requesting a response from the Optimization API
function assembleQueryURL() {
// Store the location of the truck in a variable called coordinates
var coordinates = [truckLocation];
var distributions = [];
keepTrack = [truckLocation];
// Create an array of GeoJSON feature collections for each point
var restJobs = objectToArray(pointHopper);
// If there are any orders from this restaurant
if (restJobs.length > 0) {
// Check to see if the request was made after visiting the restaurant
var needToPickUp = restJobs.filter(function(d, i) {
return d.properties.orderTime > lastAtRestaurant;
}).length > 0;
// If the request was made after picking up from the restaurant,
// Add the restaurant as an additional stop
if (needToPickUp) {
var restaurantIndex = coordinates.length;
// Add the restaurant as a coordinate
coordinates.push(warehouseLocation);
capturaCoordenada = coordinates; //Retorna a coordenada clicada
capturaCoordenada.push();

// push the restaurant itself into the array
keepTrack.push(pointHopper.warehouse);
}
restJobs.forEach(function(d, i) {
// Add dropoff to list
keepTrack.push(d);
coordinates.push(d.geometry.coordinates);
// if order not yet picked up, add a reroute
if (needToPickUp && d.properties.orderTime > lastAtRestaurant) {
distributions.push(restaurantIndex + ',' + (coordinates.length - 1));
}
});
}
// Set the profile to `driving`
// Coordinates will include the current location of the truck,
return 'https://api.mapbox.com/optimized-trips/v1/mapbox/driving/' + coordinates.join(';') + '?distributions=' + distributions.join(';') + '&overview=full&steps=true&geometries=geojson&source=first&access_token=' + mapboxgl.accessToken;
}
function objectToArray(obj) {
var keys = Object.keys(obj);
var routeGeoJSON = keys.map(function(key) {
return obj[key];
});
return routeGeoJSON;
}
function newDropoff(coords) {
// Store the clicked point as a new GeoJSON feature with
// two properties: `orderTime` and `key`
var pt = turf.point(
[coords.lng, coords.lat],
{
orderTime: Date.now(),
key: Math.random()
}
);
dropoffs.features.push(pt);
pointHopper[pt.properties.key] = pt;
// Make a request to the Optimization API
$.ajax({
method: 'GET',
url: assembleQueryURL(),
}).done(function(data) {
// Create a GeoJSON feature collection
var routeGeoJSON = turf.featureCollection([turf.feature(data.trips[0].geometry)]);
// If there is no route provided, reset
if (!data.trips[0]) {
routeGeoJSON = nothing;
} else {
// Update the `route` source by getting the route source
// and setting the data equal to routeGeoJSON
map.getSource('route')
.setData(routeGeoJSON);
}
if (data.waypoints.length === 12) {
for (var i = 0; i < capturaCoordenada.length; i++) {
var lat = capturaCoordenada[lat];
var long = capturaCoordenada[long];
exibeCoordenada = exibeCoordenada + "n" + capturaCoordenada[i] + capturaCoordenada[long]; }
exibeCoordenada = exibeCoordenada + "n";
// for (var i = 0; i < capturaCoordenada.length; i+=2) {
// var x = capturaCoordenada[i];
// var y = capturaCoordenada[i+1];
// exibeCoordenada = exibeCoordenada + "n" + capturaCoordenada[x] + capturaCoordenada[y]; }
// exibeCoordenada = exibeCoordenada + "n";
window.alert(exibeCoordenada);

}
});
}
map.addLayer({
id: 'routearrows',
type: 'symbol',
source: 'route',
layout: {
'symbol-placement': 'line',
'text-field': '▶',
'text-size': [
"interpolate",
["linear"],
["zoom"],
12, 24,
22, 60
],
'symbol-spacing': [
"interpolate",
["linear"],
["zoom"],
12, 30,
22, 160
],
'text-keep-upright': false
},
paint: {
'text-color': '#3887be',
'text-halo-color': 'hsl(55, 11%, 96%)',
'text-halo-width': 3
}
}, 'waterway-label');
});     </script>

最好不要在数据库中存储坐标,而是在Xml(gpx文件(输出中详细说明信息,在数据库中只存储文件名,并将文件保存在文件夹中。这就是你总是可以将路线下载为gpx文件,或者将其移动到其他地方,或者手动调整。将坐标保存在数据库中,我个人认为这不是一个灵活的解决方案。

最新更新