IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JavaScript Discussion :

[Leaflet] Chargement automatique des données avec leaflet et openstreetmap


Sujet :

JavaScript

  1. #1
    Nouveau Candidat au Club
    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Mai 2016
    Messages
    1
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux

    Informations forums :
    Inscription : Mai 2016
    Messages : 1
    Points : 1
    Points
    1
    Par défaut [Leaflet] Chargement automatique des données avec leaflet et openstreetmap
    Bonjour,
    Je suis en train de développer une carte avec openstreetmap et leaflet.js.
    J'ai une base de données qui contient plus de 150000 données. Je ne peut pas les afficher toutes en même temps. Alors, j'ai développé un script php qui va interroger la base de donnée et qui retourne un code GEOJSON. Il sera appelé par le script javascript dès lors que la vue de la carte aura changé (déplacement, zoom).
    Je me base sur ce projet que j'ai trouvé sur github: https://github.com/chillly/plaques

    Mes scripts actuels fonctionnent bien. Le chargement automatique ne pose pas de problème et la lecture de la carte est plutôt fluide.
    Voici mes scripts actuels:

    Code PHP:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    <?php 
    include "../../../php/database.php";
    $bdd = db_connect(); //	Connexion à la base de donnée
    // uncomment below to turn error reporting on
    ini_set('display_errors', 1);
    error_reporting(E_ALL);
     
    if (isset($_GET['bbox'])) {
    	$bbox=$_GET['bbox'];
    } else {
    	// invalid request
    	$ajxres=array();
    	$ajxres['resp']=4;
    	$ajxres['dberror']=0;
    	$ajxres['msg']='missing bounding box';
    	sendajax($ajxres);
    }
    // split the bbox into it's parts
    list($left,$bottom,$right,$top)=explode(",",$bbox);
     
    $sql="SELECT data_id,data_latitude,data_longitude,data_portee FROM porteerdi.donnees WHERE data_longitude>=".$left." AND data_longitude<=".$right." AND data_latitude>=".$bottom." AND data_latitude<=".$top;
    $data = array(); //setting up an empty PHP array for the data to go into
    if($result = db_query($bdd, $sql)) {
      while ($row = mysqli_fetch_assoc($result)){
        $data[] = $row;
      }
    }
    $ajxres=array(); // place to store the geojson result
    $features=array(); // array to build up the feature collection
    $ajxres['type']='FeatureCollection';
     
    for($i=0;$i<count($data)-1;$i++){
    	$lat=$data[$i]['data_latitude'];
    	$lon=$data[$i]['data_longitude'];
    	$prop=array();
    	$prop['plaqueid']=$data[$i]['data_id'];
    	$prop['plaquedesc']=$data[$i]['data_portee'];
    	$prop['colour']="blue";
    	$prop['imageid']="op6298.jpg";
    	$f=array();
    	$geom=array();
    	$coords=array();
     
    	$geom['type']='Point';
    	$coords[0]=floatval($lon);
    	$coords[1]=floatval($lat);
     
    	$geom['coordinates']=$coords;
    	$f['type']='Feature';
    	$f['geometry']=$geom;
    	$f['properties']=$prop;
     
    	$features[]=$f;
     
    }
     
    // add the features array to the end of the ajxres array
    $ajxres['features']=$features;
    // tidy up the DB
    $db = null;
    sendajax($ajxres); // no return from there
     
    function sendajax($ajx) {
    	// encode the ajx array as json and return it.
    	$encoded = json_encode($ajx);
    	exit($encoded);
    }
    ?>
    Code JAVASCRIPT:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    /*
     * global variables
     */
    var map;            // global map object
    var lyrOsm;         // the Mapnik base layer of the map
    var lyrPlq;         // the geoJson layer to display plaques with
    var blueicon;       // a blue icon for blue plaques 
    var greenicon;      // a green icon for green plaques
    var whiteicon;      // a white icon for white plaques
     
    // when the whole document has loaded call the init function
    $(document).ready(init);
     
    function init() {       
        // map stuff
        // create the icons
        blueicon=L.icon({
            iconUrl: 'images/blueplaque.png',
            iconSize:     [24, 24], // size of the icon
            iconAnchor:   [12, 23], // point of the icon which will correspond to marker's location
            popupAnchor:  [0, -12]  // point from which the popup should open relative to the iconAnchor
        });
        greenicon=L.icon({
            iconUrl: 'images/greenplaque.png',
            iconSize:     [24, 24], // size of the icon
            iconAnchor:   [12, 23], // point of the icon which will correspond to marker's location
            popupAnchor:  [0, -12]  // point from which the popup should open relative to the iconAnchor
     
        });
        whiteicon=L.icon({
            iconUrl: 'images/whiteplaque.png',
            iconSize:     [24, 24], // size of the icon
            iconAnchor:   [12, 23], // point of the icon which will correspond to marker's location
            popupAnchor:  [0, -12]  // point from which the popup should open relative to the iconAnchor
     
        });
     
        // base layer
        var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';    
        var osmAttrib='Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors';
     
        lyrOsm = new L.TileLayer(osmUrl, {
            minZoom: 9, 
            maxZoom: 19, 
            attribution: osmAttrib
        });
     
        // a geojson layer
        lyrPlq = L.geoJson(null, {
            pointToLayer: setIcon
            }
        );
     
        // set the starting location for the centre of the map
        var start = new L.LatLng(53.7610,-0.3529);  
     
        // create the map
        map = new L.Map('mapdiv', {     // use the div called mapdiv
            center: start,              // centre the map as above
            zoom: 12,                   // start up zoom level
            layers: [lyrOsm,lyrPlq]     // layers to add 
        });
     
        // create a layer control
        // add the base layers
        var baseLayers = {
            "OpenStreetMap": lyrOsm
        };
     
        // add the overlays
        var overlays = {
            "Plaques": lyrPlq
        };
     
        // add the layers to a layer control
        L.control.layers(baseLayers, overlays).addTo(map);
     
        // create the hash url on the browser address line
        var hash = new L.Hash(map);
     
        map.on('moveend', whenMapMoves);
     
        askForPlaques();
    }
     
    function whenMapMoves(e) {
        askForPlaques();
    }
     
    function setIcon(feature,ll) {
        var plq; 
        plq=L.marker(ll, {icon: greenicon});
        plq.bindPopup(feature.properties.plaquedesc);
        return plq;
    }
     
    function askForPlaques() {
        var data='bbox=' + map.getBounds().toBBoxString();
        $.ajax({
            url: 'ajax/ajxplaques.php',
            dataType: 'json',
            data: data,
            success: showPlaques
        });
    }
     
    function showPlaques(ajxresponse) {
        lyrPlq.clearLayers();
        lyrPlq.addData(ajxresponse);
    }

    Je souhaite maintenant afficher des lignes entre les points et ne plus afficher ces points.
    J'ai modifié mon code PHP pour que le code geojson soit compatible avec les lignes.

    Code PHP:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
     
    <?php 
    include "../../../php/database.php";
    $bdd = db_connect(); // Connexion à la base de donnée
    // uncomment below to turn error reporting on
    ini_set('display_errors', 1);
    error_reporting(E_ALL);
     
    if (isset($_GET['bbox'])) {
        $bbox=$_GET['bbox'];
    } else {
        // invalid request
        $ajxres=array();
        $ajxres['resp']=4;
        $ajxres['dberror']=0;
        $ajxres['msg']='missing bounding box';
        sendajax($ajxres);
    }
    // split the bbox into it's parts
    list($left,$bottom,$right,$top)=explode(",",$bbox);
     
    // open the database
    $sql="SELECT data_id,data_latitude,data_longitude,data_portee FROM porteerdi.donnees WHERE data_longitude>=".$left." AND data_longitude<=".$right." AND data_latitude>=".$bottom." AND data_latitude<=".$top;
    $data = array(); //setting up an empty PHP array for the data to go into
    if($result = db_query($bdd, $sql)) {
      while ($row = mysqli_fetch_assoc($result))
      {
        $data[] = $row;
      }
    }
     
    $ajxres=array(); // place to store the geojson result
    $features=array(); // array to build up the feature collection
    $ajxres['type']='FeatureCollection';
     
    for($i=0;$i<count($data)-1;$i++){
        $lat1=$data[$i]['data_latitude'];
        $lon1=$data[$i]['data_longitude'];
        $lat2=$data[$i+1]['data_latitude'];
        $lon2=$data[$i+1]['data_longitude'];
        $prop=array();
        $prop['plaqueid']=$data[$i]['data_id'];
        $prop['plaquedesc']=$data[$i]['data_portee'];
        $prop['colour']="blue";
        $prop['imageid']="op6298.jpg";
        $f=array();
        $geom=array();
        $coords=array();
        $geom['type']='Point';
        $coords[]=array(floatval($lon1),floatval($lat1));
        $coords[]=array(floatval($lon2),floatval($lat2));
        $geom['coordinates']=$coords;
        $f['type']='Feature';
        $f['geometry']=$geom;
        $f['properties']=$prop;
        $features[]=$f;
    }
     
    // add the features array to the end of the ajxres array
    $ajxres['features']=$features;
    // tidy up the DB
    $db = null;
    sendajax($ajxres); // no return from there
     
    function sendajax($ajx) {
        // encode the ajx array as json and return it.
        $encoded = json_encode($ajx);
        exit($encoded);
    }
    ?>
    Maintenant je ne sais pas comment modifier le code JS pour qu'il puisse afficher des lignes à la place des points.

  2. #2
    Modérateur

    Avatar de NoSmoking
    Homme Profil pro
    Inscrit en
    Janvier 2011
    Messages
    17 075
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Janvier 2011
    Messages : 17 075
    Points : 44 657
    Points
    44 657
    Par défaut
    Bonjour,
    J'ai modifié mon code PHP pour que le code geojson soit compatible avec les lignes.
    dans ce cas pourquoi ne fais tu pas directement lors du retour de ta requête un
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    var oGeoJson = L.geoJson( ajxresponse).addTo( oMap);

Discussions similaires

  1. Réponses: 1
    Dernier message: 08/05/2015, 17h30
  2. Problème de chargement des données avec hibernate
    Par nasnet dans le forum Langages de programmation
    Réponses: 0
    Dernier message: 02/07/2013, 17h46
  3. [XL-2007] Copie automatique des données de TextBox avec calcul
    Par Jcorbeaux dans le forum Macros et VBA Excel
    Réponses: 1
    Dernier message: 18/01/2012, 23h52
  4. Entrer automatiquement des données Avec MySQL, JS et php
    Par HWICE dans le forum Général JavaScript
    Réponses: 5
    Dernier message: 11/04/2008, 16h40
  5. Processus de chargement des données (avec talend)
    Par szoubir dans le forum Développement de jobs
    Réponses: 2
    Dernier message: 27/04/2007, 12h17

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo