2013-10-02 48 views
0

我一直在一個小應用程序的朋友現在我編碼MySQL查詢與JSON編碼一個MySQL陣列並顯示在谷歌地圖

<?php 
    include 'dbconnect.php'; 
    $result = mysql_query("SELECT * FROM coords ORDER BY name DESC") or die ("Could not 
    query"); 
    while($row = mysql_fetch_array($result)) { 
     $r[] = array(
    "name" => $row['name'], 
    "lat" => $row['lat'], 
     "lng" => $row['lng'], 
     "speed" => $row['speed'], 
     "altitude" => $row['altitude'], 
    "distance" => $row['distance'] 
     ); 
     } 
    $encoded = json_encode($r); 
    echo$encoded; 
    mysql_close($conn); 

    ?> 

的問題是有關聯的陣列位置的關鍵每個條目告訴JSON,這整個事情是一個關鍵

 Array(
    [1] = ( "name" => $row['name'], 
    "lat" => $row['lat'], 
     "lng" => $row['lng'], 
     "speed" => $row['speed'], 
     "altitude" => $row['altitude'], 
     "distance" => $row['distance']), 
    [2] = ("name" => $row['name'], 
    "lat" => $row['lat'], 
     "lng" => $row['lng'], 
     "speed" => $row['speed'], 
     "altitude" => $row['altitude'], 
     "distance" => $row['distance']))); 

對數據庫中的每一行基本上我要對數據庫中的每一行解析到一個數組用自己的鑰匙,所以我可以把它作爲一個javascript對象並在谷歌地圖上繪製它。

ive tried 

    <?php 
    include 'dbconnect.php'; 
    $count = 0; 
    $result = mysql_query("SELECT * FROM coords ORDER BY name DESC") or die ("Could not 
    query"); 
    while($row = mysql_fetch_array($result)) { 
     $count = $count + 1; 
    $r[$count] = array(
    "name" => $row['name'], 
    "lat" => $row['lat'], 
     "lng" => $row['lng'], 
     "speed" => $row['speed'], 
     "altitude" => $row['altitude'], 
    "distance" => $row['distance'] 
     ); 
     } 
    $encoded = json_encode($r); 
    echo$encoded; 
    mysql_close($conn); 

    ?> 

但這並沒有工作,而且那裏是我的json代碼im不知道它的權利。下面是我的地圖代碼,你可以看看JSON代碼的部分,並告訴我是否應該調用我想寫在我的PHP文件中的數組。另外,如果我正在爲陣列繪製標記。由於

var watchID; 
    var latitudeAndLongitudeCurrent; 
    var route = false; 
    var firstMapCall; 
    var directionsDisplay;           // Declare a variable 
    of renderer object 
    var directionsService = new google.maps.DirectionsService();  // Instantiate a 
    directions service. 
    var map; 
    var currentMarker; 
    var carMarker; 
    var usermarker; 
    var markloc; 
    var myOptions = 
    { 
    zoom:14, 
    mapTypeId: google.maps.MapTypeId.ROADMAP, 

     enableHighAccuracy: true, 
    zoomControlOptions: { 
     position: google.maps.ControlPosition.TOP_RIGHT 
    }, 
    maximumAge: 10000 
    }; 


    function initializeMyMap() 
    { 
     directionsDisplay = new google.maps.DirectionsRenderer();  // Instantiate a 
     renderer object. 
    //directionsDisplay.suppressMarkers = true; //removes direction markers 
     map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
     directionsDisplay.setMap(map);         // bind the map to 
    the renderer 
    } 

    function showLocation(){ 
    firstMapCall = true; 
    //if initalize hasn't been called, call it 
    if(directionsDisplay == null) { 
     initializeMyMap(); 
    } 
    watchID = navigator.geolocation.watchPosition(onSuccessShowLoc, onError, myOptions); 
    } 

    function setMapBounds(position){ 
    var mapBounds = new google.maps.LatLngBounds(); 
    mapBounds.extend(position); 
     map.fitBounds(mapBounds); 
     zoomChangeBoundsListener = 
     google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) { 
     if (this.getZoom()){ 
      this.setZoom(18); 
     } 
     }); 
     resize(); 
    } 







    // onSuccess Geolocation 
    function onSuccessShowLoc(position) { 
     latitudeAndLongitudeCurrent = new google.maps.LatLng(position.coords.latitude, 
     position.coords.longitude); 

     if(firstMapCall == true){ 
      var result = retrieveLocation(); 
      setMapBounds(latitudeAndLongitudeCurrent); 
      if(result != null){ 
       addCarMarker(result); 
      } 
      firstMapCall = false; 
     } 
     deleteOverlays(); 
     addCurrentLocMarker(latitudeAndLongitudeCurrent); 

    //ajax  
    var ajaxRequest; 
     try{ 
    // Opera 8.0+, Firefox, Safari 
    ajaxRequest = new XMLHttpRequest(); 
    }catch (e){ 
    // Internet Explorer Browsers 
    try{ 
     ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); 
    }catch (e) { 
     try{ 
     ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
     }catch (e){ 
     // Something went wrong 
     alert("Your browser broke!"); 
     return false; 
     } 
    } 
    } 

    // This sets the users location in the database 
    var lat = position.coords.latitude; 
    var lng = position.coords.longitude; 
    var parseid = id; 
    var queryString = "?lat=" + lat ; 
    queryString += "&lng=" + lng + "&id=" + parseid; 
    console.log('string combination'); 
    ajaxRequest.open("GET", "data.php" + queryString, true); 
    ajaxRequest.send(null); 
    console.log('executed');   
    } 


    // Removes the overlays from the map, but keeps them in the array 
    function deleteOverlays() { 
     if (currentMarker) { 
      currentMarker.setMap(null); 
     } 
    } 


    function deleteCarOverlay() { 
     if (carMarker) { 
      carMarker.setMap(null); 
     } 
    } 


    function deleteUserOverlay() { 
     if (usermarker) { 
      usermarker.setMap(null); 
     } 
    } 

    function addCurrentLocMarker(location) { 
     marker = new google.maps.Marker({ 
     position: location, 
     icon: 'http://www.wolfdoginfo.net/app/snowboarding.png', 
     map: map 
    }); 
    currentMarker = marker; 


    } 

    function addCarMarker(location) { 
     marker = new google.maps.Marker({ 
      draggable: true, 
      raiseOnDrag: false, 
      icon:'http://www.wolfdoginfo.net/app/revolt.png', 
      map: map, 
      position: location 
    }); 
    carMarker = marker; 
    } 




     var myVar=setInterval(function(){showData()},3000); 


    function showData(str) 
    { 
    calluserlocation(); 
     } 

     function calluserlocation(){ 
     console.log('calluserlocation fires'); 
     $.ajax({ 
    url: "getdata.php", 
    type: "GET", 
    dataType: "json", 
    success: function(data) { for (var i = 0; i < data.length; i++) { markloc = new 
     google.maps.LatLng(data[i].b, data[i].c); adddata(markloc); } }, error: 
     function(data) {  console.log("error with the json"); } }); 
    console.log("sucessful run of function"); 
     } 


    function adddata(markloc){ 
    marker = new google.maps.Marker({ 
    position: markloc, 
    icon: 'http://www.wolfdoginfo.net/app/cropcircles.png', 
    map: map 
     }); 
    deleteUserOverlay(); 
    usermarker = marker; 
    } 


    function calcRoute() 
    { 
    var theDestination = retrieveLocation(); 
    if(theDestination == null){ 
     alert("Error: No Friend meeting place has been saved."); 
     return null; 
    } 
    var request = // Instantiate a DirectionsRequest object 
    {               
     //origin is LatLng object 
     origin: latitudeAndLongitudeCurrent, 
     //destination is LatLng object 
     destination: theDestination, 
     travelMode: google.maps.DirectionsTravelMode.WALKING 
    }; 




    directionsService.route(request, // call route() to request directions service 
    function(result, status)  
    {  
     if (status == google.maps.DirectionsStatus.OK) 
     { 
     directionsDisplay.setOptions({ preserveViewport: true }); 
     directionsDisplay.setDirections(result);     // draw the routes 
     // put text directions on directions_panel 
     directionsDisplay.setPanel(document.getElementById("directions_panel")); 
     route=true;    
     } 
    } 
    ); 
    } 



    function textDirections() 
    { 
    if(route == false){ 
    calcRoute(); 
    } 
    } 


    function resize(){ 
    var map_page = document.getElementById('show'); 
    var map_container = document.getElementById('the_map_container'); 
    var header = document.getElementById('thehead'); 
    var newHeight = map_page.offsetHeight - 170; 
    map_container.style.height = newHeight + 'px'; 

    // trigger a resize event on the map so it reflects the new size 
    if(map != null) { 
    google.maps.event.trigger(map, 'resize'); 
    } 
    } 
+0

首先,停止使用mysql。它已被棄用。使用mysqli或PDO。 –

+0

你想成爲你的鑰匙什麼價值?您的帖子不清楚 – Machavity

+0

我想要用戶名作爲值名稱抱歉... @machavity因爲即時通訊將顯示在用戶的朋友列表中的每個人的位置,因此我認爲使用名稱每個人將是最好的或一個數字ID作品以及 – user2030485

回答

0

如果你想你的名字作爲鍵,然後做這個

$r = array(); // A best practice to declare it's an array 
while($row = mysql_fetch_assoc($result)) { // fetch_assoc gives you keys based on your field names 
    $r[$row['name']] = array(...); 
} 

此外,PSA,一定要使用的mysqli像MySQL現在已經貶值。