Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WayPoints from GeoJson #709

Open
Didier-W opened this issue Dec 9, 2024 · 7 comments
Open

WayPoints from GeoJson #709

Didier-W opened this issue Dec 9, 2024 · 7 comments
Labels

Comments

@Didier-W
Copy link

Didier-W commented Dec 9, 2024

Hello,
I want to use the LeafLet Routing Machine solution with a fixed starting point that will be the same as the arrival point whose coordinates I know. For this, no problem.
I want the intermediate WayPoints coordinates to come from a GeoJson structure of the following type:

const sites_culture = {
"type": "FeatureCollection",
"name": "sites_culture",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "name": "MUSEON ARLATEN", "address": "29 Rue de la République", "commune": "13200 ARLES", "tel": "04 13 31 51 79/99", "policy": "Culture" }, "geometry": { "type": "Point", "coordinates": [ 4.626015921662016, 43.676486873401274 ] } },
{ "type": "Feature", "properties": { "name": "MDAA - ARLES", "address": "29 Rue de la République", "municipality": "13200 ARLES", "tel": "04 13 31 51 03", "politics": "Culture" }, "geometry": { "type": "Point", "coordinates": [ 4.616614226966669, 43.67205666986852 ] } },
{ "type": "Feature", "properties": { "name": "Etang des Aulnes - SAINT-MARTIN-DE-CRAU", "address": "1676 Chemin d'Istres à l'Etang des Aulnes", "municipality": "13310 SAINT-MARTIN-DE-CRAU", "tel": "04 13 31 63 96", "politics": "Culture" }, "geometry": { "type": "Point", "coordinates": [ 4.78871613086454, 43.59676153502288 ] } },
{ "type": "Feature", "properties": { "name": "Château d'Avignon - SAINTES-MARIES-DE-LA-MER", "address": "RD 570", "municipality": "13460 SAINTES-MARIES-DE-LA-MER", "tel": "04 13 31 13 13", "politics": "Culture" }, "geometry": { "type": "Point", "coordinates": [ 4.411424362314144, 43.55804568265447 ] } },
{ "type": "Feature", "properties": { "name": "Archives et Bibliothèque Départementales des Bouches-du Rhône", "adresse": "18 - 20 Rue Mirès", "commune": "13003 MARSEILLE", "tel": "04 13 31 82 00", "politique": "Culture" }, "geometry": { "type": "Point", "coordinates": [ 5.369675449734724, 43.31173470954983 ] } }
]
}

How should I call these coordinates in the intermediate WayPoints?

var control = L.Routing.control({
waypoints: [
L.latLng(43.27493085740852, 5.695082510623004),
L.latLng(?, ?),
...
L.latLng(?, ?),
L.latLng(43.27493085740852, 5.695082510623004)
],
router: new L.Routing.osrmv1({
language: 'en',
profile: 'car'
}),
geocoder: L.Control.Geocoder.nominatim({}),
routeWhileDragging: true,
reverseWaypoints: true,
fitSelectedRoutes: true
}).addTo(map);

Thank you in advance for your help.
Didier

@curtisy1
Copy link
Collaborator

curtisy1 commented Dec 9, 2024

Hey @Didier-W
if you know the coordinates beforehand, you can add them as waypoints directly by spreading them after mapping

var control = L.Routing.control({
waypoints: [
L.latLng(43.27493085740852, 5.695082510623004),
...sites_culture.features.map(x => L.latlng(x.geometry.coordinates))
L.latLng(43.27493085740852, 5.695082510623004)
],
router: new L.Routing.osrmv1({
language: 'en',
profile: 'car'
}),
geocoder: L.Control.Geocoder.nominatim({}),
routeWhileDragging: true,
reverseWaypoints: true,
fitSelectedRoutes: true
}).addTo(map);

You might have to do some more manipulation if your GeoJson has other types than points (with more than one coordinate)

If you don't know them when initializing the routing machine, you can call setWaypoints like in this example

const waypoints = control.getWaypoints();
control.setWaypoints([waypoints[0], ...sites_culture.features.map(x => L.latlng(x.geometry.coordinates)), waypoints[waypoints.length - 1]]);

I hope this helps. If you need further help, feel free to let me know

@Didier-W
Copy link
Author

Didier-W commented Dec 9, 2024

Good evening,
Sorry for my English, it's not my native language.
I'm tinkering with Leaflet, GeoJson and JavaScript (I'm more comfortable with PHP and SQL :-)).
Thank you for your answer. I tried, but it doesn't work.
Here is the code of my page:

<title>Leaflet Routing Machine Example</title> <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-routing-machine/3.2.5/leaflet-routing-machine.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/perliedman-leaflet-control-geocoder/1.5.5/Control.Geocoder.min.js"></script> <style> .map { position: absolute; width: 100%; height: 100%; } </style>
<script>
  var mymap = L.map('mapid').setView([43.27493085740852, 5.695082510623004], 10);

console.log(mymap);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(mymap);

var sites_culture = {
"type": "FeatureCollection",
"name": "sites_culture",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "name": "MUSEON ARLATEN", "address": "29 Rue de la République", "commune": "13200 ARLES", "tel": "04 13 31 51 79/99", "policy": "Culture" }, "geometry": { "type": "Point", "coordinates": [ 4.626015921662016, 43.676486873401274 ] } },
{ "type": "Feature", "properties": { "name": "MDAA - ARLES", "address": "29 Rue de la République", "municipality": "13200 ARLES", "tel": "04 13 31 51 03", "politics": "Culture" }, "geometry": { "type": "Point", "coordinates": [ 4.616614226966669, 43.67205666986852 ] } },
{ "type": "Feature", "properties": { "name": "Etang des Aulnes - SAINT-MARTIN-DE-CRAU", "address": "1676 Chemin d'Istres à l'Etang des Aulnes", "municipality": "13310 SAINT-MARTIN-DE-CRAU", "tel": "04 13 31 63 96", "politics": "Culture" }, "geometry": { "type": "Point", "coordinates": [ 4.78871613086454, 43.59676153502288 ] } },
{ "type": "Feature", "properties": { "name": "Château d'Avignon - SAINTES-MARIES-DE-LA-MER", "address": "RD 570", "municipality": "13460 SAINTES-MARIES-DE-LA-MER", "tel": "04 13 31 13 13", "politics": "Culture" }, "geometry": { "type": "Point", "coordinates": [ 4.411424362314144, 43.55804568265447 ] } },
{ "type": "Feature", "properties": { "name": "Archives et Bibliothèque Départementales des Bouches-du Rhône", "adresse": "18 - 20 Rue Mirès", "commune": "13003 MARSEILLE", "tel": "04 13 31 82 00", "politique": "Culture" }, "geometry": { "type": "Point", "coordinates": [ 5.369675449734724, 43.31173470954983 ] } }
]
};

var control = L.Routing.control({
waypoints: [
L.latLng(43.27493085740852, 5.695082510623004),
sites_culture.features.map(x => L.latlng(x.geometry.coordinates)),
L.latLng(43.27493085740852, 5.695082510623004)
],
router: new L.Routing.osrmv1({
language: 'en',
profile: 'car'
}),
geocoder: L.Control.Geocoder.nominatim({}),
routeWhileDragging: true,
reverseWaypoints: true,
fitSelectedRoutes: true
}).addTo(mymap);

</script>

Thanks again for the help you can all give me.
Didier

@Didier-W
Copy link
Author

Hello,
ChatGPT gave me the solution below that works. But I have to continue because I now want to sort the stages of my route according to the properties of the GeoJson :

<title>Leaflet Routing Machine Example</title> <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-routing-machine/3.2.5/leaflet-routing-machine.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/perliedman-leaflet-control-geocoder/1.5.5/Control.Geocoder.min.js"></script> <style> .map { position: absolute; width: 100%; height: 100%; } </style>
<!-- Chargement des coordonnées des Sites -->
<script type="text/javascript" src="../zonages/OLD/sites_routes.geojson"></script>

<script>
  var mymap = L.map('mapid').setView([43.27493085740852, 5.695082510623004], 10);
  L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(mymap);

  // Point de départ et d'arrivée
  var startEndPoint = L.latLng(43.3159505241721, 5.407132739677479);

  // Extraire les coordonnées des points intermédiaires
  var waypoints = [startEndPoint];
  sites_routes.features.forEach(function(feature) {
      var coords = feature.geometry.coordinates;
      waypoints.push(L.latLng(coords[1], coords[0])); // Inverser latitude et longitude
  });
  waypoints.push(startEndPoint); // Retour au point de départ

  // Créer le contrôle de routage
  L.Routing.control({
      waypoints: waypoints,
      router: new L.Routing.osrmv1({
          language: 'en',
          profile: 'car'
      }),
      geocoder: L.Control.Geocoder.nominatim({}),
      routeWhileDragging: true,
      reverseWaypoints: true,
      fitSelectedRoutes: true
  }).addTo(mymap);
</script>

Is it possible to add a filter like this one :

filter: function(feature, layer) {
if(feature.properties.politique === "Routes") return true
}

Thank you.
Have a nice day.

@curtisy1
Copy link
Collaborator

Do you only want to add the waypoints if they are of politique "Routes"?
If so, you can do something like this and it should work:

sites_routes.features.forEach(function(feature) {
	var coords = feature.geometry.coordinates;
	if (feature.properties.politique === "Routes") {
		waypoints.push(L.latLng(coords[1], coords[0])); // Inverser latitude et longitude
	}
});

@Didier-W
Copy link
Author

Bonjour,
Merci pour votre aide.
J'ai résolu mon problème et sui même allé un peu plus loin en ajoutant des variables à mon URL qui sont exploitées par le code et permettent de faire un tri dans le fichier sites.geojson :

<!-- Chargement des coordonnées des Sites -->
<script type="text/javascript" src="../zonages/sites.geojson"></script>

<script>

    const urlParams = new URLSearchParams(window.location.search);
    const jour = urlParams.get('jour');
    const passage = urlParams.get('passage');
    const secteur = urlParams.get('secteur');

    var mymap = L.map('mapid').setView([43.27493085740852, 5.695082510623004], 10);
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(mymap);
  
    // Point de départ et d'arrivée
    var startEndPoint = L.latLng(43.31605078149452, 5.4071400476197224);
  
    // Extraire les coordonnées des points intermédiaires
    var waypoints = [startEndPoint];
    sites.features.forEach(function(feature) {
        var properties = feature.properties;
        var coords = feature.geometry.coordinates;
  
        // Appliquer les filtres
        if (jour === "lundi") {
            if (
              properties.lundi === passage &&
              properties.secteur === secteur
          ) {
              waypoints.push(L.latLng(coords[1], coords[0])); // Ajouter le point correspondant
          }
        }
        if (jour === "mardi") {
            if (
              properties.mardi === passage &&
              properties.secteur === secteur
          ) {
              waypoints.push(L.latLng(coords[1], coords[0])); // Ajouter le point correspondant
          }
        }
        if (jour === "mercredi") {
            if (
              properties.mercredi === passage &&
              properties.secteur === secteur
          ) {
              waypoints.push(L.latLng(coords[1], coords[0])); // Ajouter le point correspondant
          }
        }
        if (jour === "jeudi") {
            if (
              properties.jeudi === passage &&
              properties.secteur === secteur
          ) {
              waypoints.push(L.latLng(coords[1], coords[0])); // Ajouter le point correspondant
          }
        }
        if (jour === "vendredi") {
            if (
              properties.vendredi === passage &&
              properties.secteur === secteur
          ) {
              waypoints.push(L.latLng(coords[1], coords[0])); // Ajouter le point correspondant
          }
        }
    });
    waypoints.push(startEndPoint); // Retour au point de départ
  
    // Créer le contrôle de routage
    L.Routing.control({
        waypoints: waypoints,
        router: new L.Routing.osrmv1({
            language: 'en',
            profile: 'car'
        }),
        geocoder: L.Control.Geocoder.nominatim({}),
        routeWhileDragging: true,
        reverseWaypoints: true,
        fitSelectedRoutes: true
    }).addTo(mymap);

  </script>

Bonne journée.
Didier

@curtisy1
Copy link
Collaborator

De rien. Si je peux vous recommander une petite amélioration du code, vous pouvez utiliser la variable jour avec les arrays directement. Avec ce code, vous avez un seul point pour ajouter les coordonnées au array

            if (
              properties[jour] === passage &&
              properties.secteur === secteur
          ) {
              waypoints.push(L.latLng(coords[1], coords[0])); // Ajouter le point correspondant
          }

I hope my French was not too bad 😆 it's been a few years since I've spoken French

@Didier-W
Copy link
Author

Bonsoir,
Je vous remercie pour cette suggestion. Je vais la tester.
Pour ce qui concerne votre français, il est parfait : aucune faute d'orthographe, pas d'erreur de style. Bravo !
Passez une excellente soirée.
A bientôt.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants