2016-03-23 17 views
0

Leaflet için yeni ve işaretleyicileri bir MySQL veritabanından bir broşür haritasına nasıl yükleyeceğimi merak ediyordum.MySQL'den PHP ve ajax kullanarak işaretleyiciler nasıl yüklenir?

İşaretçiler yalnızca harita başlatıldığında değil, bir işlevle yüklemek istemiyorum çünkü kullanıcının örneğin tarihler arasında seçim yapmasını ve ardından bu tarihlerdeki işaretçileri yüklemesini istiyorum. Şimdiye kadar aşağıdakileri yaptım, ancak bir hata alıyorum: Hatalı yaptığımdan emin değilim.

jQuery

$(document).ready(function() { 
    var markerpositions; 
    var map = L.map('map').setView([-55.7770641,55.6602758], 13); 
    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { 
     maxZoom: 19, 
     attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' 
    }).addTo(map); 
    getlocations(); 
    var marker = L.marker(markerpositions).addTo(map); 


function getlocations(){ 
var id = "1"; 

    $.ajax({ 
     type: "POST", 
     url: "getlocationstomap.php", 
     data: {id:id}, 
     dataType: 'json', 
     cache: false, 
    }) 
    .success(function(response) { 
     if(!response.errors && response.result) { 

      $.each(response.result, function(index, value) { 
       markerpositions = '['+value[0]+','+value[1]+']'; 
      }); 


     } else { 
      $.each(response.errors, function(index, value) { 
       $('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>') 
      }); 
     } 
    }); 
} 
}) 

PHP (getlocationstomap.php) Eğer ajax yanıtı ayrıştırmak zaman

<?php 
// assign your post value 
$inputvalues = $_POST; 

// assign result vars 
$errors = false; 
$result = false; 

$mysqli = new mysqli('localhost', "root", "", "traxi"); 

/* check connection */ 
    if (mysqli_connect_errno()) { 
     printf("Connect failed: %s\n", mysqli_connect_error()); 
     exit(); 
    } 

    // escape your values 
    foreach ($inputvalues as $key => $value) { 
     if(isset($value) && !empty($value)) { 
      $inputvalues[$key] = $mysqli->real_escape_string($value); 
     } else { 
      $errors[$key] = 'The field '.$key.' is empty'; 
     } 
    } 

if(!$errors) { 
     // select your query 
     $addresult = " 
      SELECT `latitude`, `longitude` 
      FROM `positions` 
      WHERE `deviceid` = '" . $inputvalues['id'] . "' 

     "; 
//$returnResult = array(); 
     if($result = $mysqli->query($addresult)) { 
      // collect results 
      while($row = $result->fetch_all()) 
      { 
       // assign to new array 
       // make returnResult an array for multiple results 
       $returnResult = $row; 
      } 
     } 
    } 

    // close connection 
    mysqli_close($mysqli); 

    // print result for ajax request 
    echo json_encode(['result' => $returnResult, 'errors' => $errors]); 

    exit; 
?> 

cevap

0

, dün bu yüzden sadece tekrar tekrar değişken markerpositions üzerine yazıyorsunuz ayrıştırılmış değişken haritaya hiç eklenecektir.

Ayrıca L.marker() yönteminin giriş olarak bir diziye ihtiyacı vardır, ancak en uzun verileriniz dizi yerine markerpositions değişkeninde bir dize olarak atanır.

böyle haritaya yanıt verilerini ekleyin: Ben bunu biliyorum

$.each(response.result, function(index, value) { 
    L.marker([ value[0], value[1] ]).addTo(map); 
}); 
0

yanıtladı ve kabul ama i'de (başka bir şekilde sorunla karşılaşırsanız asla you'de hangi bir yol atmak düşünülmektedir içine koştun). PHP ve yolluyoruz çıktı üzerinde kontrol sahibi olduğunda, ben en iyisi GeoJSON biçiminde verileri oluşturmak için bulmak:

GeoJSON is a format for encoding a variety of geographic data structures.

http://geojson.org/

Bunu yapmak kolaydır ve size güçlük zaman bir sürü kaydeder istemcilerdeki verileri kullanarak ve GeoJSON teli kullanarak kolayca test edilebilir, özel olarak oluşturulmuş bir JSON yapısı ile kolayca yapamazsınız. Ayrıca, GeoJSON hemen hemen her GIS uygulaması tarafından kullanılabilir, böylece verileriniz çok sayıda uygulama arasında birbiriyle değiştirilebilir.

MySQL satırlarınızı GeoJSON özelliklerine döndürmeniz, hepsini bir GeoJSON koleksiyonuna koymanız, JSON kodlamasını yapıp istemciye göndermeniz gerekir. Orada bir kerede Leaflet'in L.GeoJSON katmanına yükleyebilirsiniz.kodunda bir örnek:

<?php 

function createFeature() { 
    $feature = new stdClass(); 
    $feature->type = 'Feature'; 
    $feature->properties = new stdClass(); 
    $feature->geometry = new stdClass(); 
    $feature->geometry->type = 'Point'; 
    $feature->geometry->coordinates = array(); 
    return $feature; 
} 

function createCollection() { 
    $collection = new stdClass(); 
    $collection->type = 'FeatureCollection'; 
    $collection->features = array(); 
    return $collection; 
} 
Şimdi

MySQL dan Satırlarınızı kapma zaman ayrı özellikler, her satır veri eklemek ve bir karşı bu özellikleri itmek:

Fonksiyonlar yeni/boş GeoJSON özellikleri ve koleksiyonları oluşturmak için toplanması ve müşteriye göndermek:

{ 
    "type": "FeatureCollection", 
    "features": [{ 
     "type": "Feature", 
     "properties": { 
      "name": "Foo" 
     }, 
     "geometry": { 
      "type": "Point", 
      "coordinates": [1, 1] 
     } 
    }, { 
     "type": "Feature", 
     "properties": { 
      "name": "Bar" 
     }, 
     "geometry": { 
      "type": "Point", 
      "coordinates": [2, 2] 
     } 
    }] 
} 
:

<?php 

$query = "SELECT name, latitude, longitude FROM locations"; 

if ($result = $mysqli->query($query)) { 

    // Create a new collection 
    $collection = createCollection(); 

    while ($row = $result->fetch_object()) { 

     // Create a new feature 
     $feature = createFeature(); 

     // Add (optional) properties to the feature 
     $feature->properties->name = $row->name; 

     // Add coordinates to geometry coordinates array 
     // Mind that GeoJSON works with lng/lat NOT lat/lng 
     $feature->geometry->coordinates[] = $row->longitude; 
     $feature->geometry->coordinates[] = $row->latitude; 

     // Add the feature to the collection's features array 
     $collection->features[] = $feature; 
    } 

    // Encode collection object to JSON and send to client 
    echo json_encode($collection); 

    $result->close(); 
} 

buna benzer bir çıkış ile son edeceğiz

Şimdi broşür çocuk oyuncağı haline, L.GeoJSON otomatik L.Marker yaratacağı yükleme 'GeoJSON noktası özelliklerinden s:

// Grab the data via jQuery's getJSON 
$.getJSON('url', function (collection) { 

    // Create new GeoJSON layer with collection and add to map 
    new L.GeoJSON(collection).addTo(map); 
}) 

kullanma özelliklerine kullanarak çok kolay L.GeoJSON' ın ​​onEachFeature yöntemi:

new L.GeoJSON(collection, { 
    'onEachFeature': function (feature, layer) { 
     layer.bindPopup(feature.properties.name); 
    } 
}).addTo(map); 

Bu, enerjik olabileceğini umuyoruz, işte bazı referans:

+0

vay benim için ideal bir yaklaşım gibi görünüyor! çok teşekkür ederim ! Kesinlikle onu okuyacağım. –

İlgili konular