0

I have been working on a little app for a friend right now I am encoding a mysql query with

    <?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);

    ?> 

The problem is there is no array position key associated with each entry to tell the json that this whole thing is a key

     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'])));

for every row in the database basically I want to parse each row of the database into an array with his own key so i can call it as a javascript object and draw it ona google map.

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);

     ?> 

but that didn't work and theen there is my json code im not sure its right. Below is my map code can you look at the section of the json code and tellme if that is how im supposed to call the array I want to write in my php file. Also if I'm drawing the marker right fro the array. Thanks

   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');
    }
    }
5
  • Firstly first, stop using mysql. It's deprecated. Use mysqli or PDO. Commented Oct 2, 2013 at 17:10
  • What value do you want to be your key? Your post isn't clear on that Commented Oct 2, 2013 at 17:12
  • I want to have the username as the value so name sorry... @machavity because im going to display the location of everyone in the friends list of the user, thus I think using the name of each person would be the best or a number id works as well Commented Oct 2, 2013 at 17:18
  • $r[$name][] = array([... row values]) Commented Oct 2, 2013 at 17:35
  • You're very close, Jacob, but your example would create $r['name'][0]['name'] He wants $r['name']['name'] Commented Oct 3, 2013 at 12:52

1 Answer 1

1

If you want your name as the key then do this

$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( ... );
}

Also, a PSA, be sure to use mysqli as mysql has been depreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.