0

我一直在为一个朋友开发一个小应用程序,现在我正在编码一个 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 代码,我不确定它是否正确。下面是我的地图代码,您可以查看 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');
    }
    }
4

1 回答 1

1

如果你想你的名字作为关键,那么就这样做

$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已经贬值了。

于 2013-10-03T12:47:19.710 回答