1

My index.php file is shown below. In which I want to show a map and multiple marker on it using json object. This code is only for one marker. Could u please tell me how can be this code modify for multiple markers and how can i access json object in $.ajax()??

<!DOCTYPE html>
<html>
  <head>
    <style>
      #map { width: 1000px;height: 500px;}
    </style>
    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>        
    <script>
      var latlng = {lat: 31.566470, lng: 74.297723};
      var marker;
      function initialize() {
        var mapCanvas = document.getElementById('map');
        var mapOptions = {
          center: latlng,
          zoom: 11,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var map = new google.maps.Map(mapCanvas, mapOptions);
        marker = new google.maps.Marker({
          position: latlng,
          title: "Hello World!",
          map: map   // replaces marker.setMap(map);
        });
        // now let's set a time interval, let's say every 3 seconds we check the position
        setInterval(
          function() {
            // we make an AJAX call
            $.ajax({
              dataType: 'JSON',   // this means the result (the echo) of the server will be readable as a javascript object
              url: 'final.php',
              success: function(data) {
                // this is the return of the AJAX call.  We can use data as a javascript object
                console.log(data);
                // now we change the position of the marker
                 marker.setPosition({lat: Number(data.lat), lng: Number(data.lng)});
              }, 
                  error(error) {
                    console.log(error);
              }

            })
          }
          , 3000    
        );
      } 
      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map"></div>
  </body>
</html>

and it is my final.php

<?php
     define('HOST','localhost');
      define('USER','root');
      define('PASS','1234');
      define('DB','coordinates');
      $con = mysqli_connect(HOST,USER,PASS,DB);
     $arr=[];
      for($x=1; $x<=3; $x++){
       $query = "SELECT id, longitude, latitude FROM data WHERE bus_id= ".$x." ORDER BY id DESC limit 1" ;
      $qry_result = mysqli_query($con,$query);// or die(mysqli_error());
    // Insert a new row in the table for each person returned

       while($row = mysqli_fetch_array($qry_result)) {
        $longitude = $row['longitude'];
         $latitude = $row['latitude']; 

        array_push($arr, [
           'lat'=>$longitude,
           'lng'=>$latitude,
           //'recs'=>$recs
         ]);
       }
      }   
$record= json_encode($arr);
echo $record;    
?>

this is my json object

[{"lat":"74.348047","lng":"31.569907"},{"lat":"74.307826","lng":"31.573289"},{"lat":"74.330023","lng":"31.558144"}]
2
  • final.php is equal to your ajax.php (url: 'ajax.php')? Commented Jan 21, 2016 at 8:43
  • @P.Frank yes you got right Commented Jan 21, 2016 at 8:46

1 Answer 1

2

The following is not tested but I think it should work. There is a function addmarker which you call in a loop to process all data returned from the ajax call. If this gets called every few seconds you also need to clear old markers from the map - hence using an array to store references to each new marker.

I found a syntax error in original code relating to the error handler - not sure if I have corrected in the right way as I do not use jQuery ~ looks ok though.

<!DOCTYPE html>
<html>
  <head>
    <style>
      #map { width: 1000px;height: 500px;}
    </style>
    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>        
    <script>
      var latlng = { lat: 31.566470, lng: 74.297723 };
      var marker;
      var map;/* make the map available in all scopes */
      var markers=[];/* container to store references to newly added markers */

      function addmarker(map, lat, lng, title ){
         /* add new marker */
        marker = new google.maps.Marker({
          position:{ lat:lat,lng:lng },
          title:title,
          draggable:true,
          map:map
        });
        /*marker.setMap( map );*/
        /* store reference */
        markers.push( marker );
      }


      function initialize() {
        var mapCanvas = document.getElementById('map');
        var mapOptions = {
          center: latlng,
          zoom: 11,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var map = new google.maps.Map(mapCanvas, mapOptions);
        marker = new google.maps.Marker({
          position: latlng,
          title: "Hello World!",
          map: map   // replaces marker.setMap(map);
        });




        setInterval(
          function() {
            $.ajax({
              dataType: 'JSON',
              url: 'ajax.php',
              success: function(data) {
                  /* clear old markers */
                  markers.forEach( function( e,i,a ){
                     e.setMap( null ); 
                  });

                  for( var o in data ){
                    var lat=Number(data[o].lat);
                    var lng=Number(data[o].lng);
                    /* Watch the console, see what you get here */

                    console.log( 'lat:%s, lng:%s',lat,lng );

                    addmarker.call( this, map, lat, lng, 'Hello World - a title!' );
                  }
              },
              error: function( err ){
                console.log( err );  
              }
            })
          }, 3000 );
      } 
      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map"></div>
  </body>
</html>

The full code I used in testing

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){

        $dbhost =   'localhost';
        $dbuser =   'root'; 
        $dbpwd  =   'xxx'; 
        $dbname =   'xxx';


        $conn = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );    

        $sql="select 
                `location_name` as 'title',
                `location_map_centre_Latitude` as 'lat',
                `location_map_centre_Longitude` as 'lng' 
            from `maps` 
                where `countryid`=171 
                order by rand() 
                limit 10";


        $res=$conn->query( $sql );
        if( $res ){

            $json=array();
            while( $rs=$res->fetch_object() ){
                $json[]=array( 'title'=>$rs->title, 'lat'=>$rs->lat, 'lng'=>$rs->lng );
            }
            header('Content-Type: application/json');
            echo json_encode( $json );
        }
        $conn->close();
        exit();
    }
?>
<!DOCTYPE html>
<html>
  <head>
    <style>
      #map { width: 1000px;height: 500px;}
    </style>
    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>        
    <script>/* initial lat/lng is in Scotland, near Forfar */
      var latlng = { lat: 56.61543329027024, lng: -2.9266123065796137 };
      var marker;
      var map;
      var markers=[];/* container to store references to newly added markers */

      function addmarker(map, lat, lng, title ){
         /* add new marker */
        marker = new google.maps.Marker({
          position:{ lat:lat,lng:lng },
          title:title,
          draggable:true,
          map:map
        });
        /* store reference */
        markers.push( marker );
      }


      function initialize() {
        var mapCanvas = document.getElementById('map');
        var mapOptions = {
          center: latlng,
          zoom: 9,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var map = new google.maps.Map(mapCanvas, mapOptions);
        marker = new google.maps.Marker({
          position: latlng,
          title: "Hello World!",
          draggable:true,
          map: map   // replaces marker.setMap(map);
        });



        /* for testing I only want it to run for a few times */
        var i=0;
        var m=10;


        var igm=setInterval(
          function() {
              /* testing */
              i++;
              if( i > m ) clearInterval( igm );
              /* testing */


            $.ajax({
              dataType:'JSON',
              method: 'post',
              url: document.location.href,
              success: function(data) {
                  /* clear old markers */
                  markers.forEach( function( e,i,a ){
                     e.setMap( null );
                     console.log( 'remove marker:%o', e ); 
                  });

                  for( var o in data ){
                    var lat=Number(data[o].lat);
                    var lng=Number(data[o].lng);
                    var title=data[o].title;

                    /* Watch the console, see what you get here */
                    console.log( 'lat:%s, lng:%s',lat,lng );
                    addmarker.call( this, map, lat, lng, title );
                  }
              },
              error: function( err ){
                console.warn( 'Error: %s',err );  
              }
            })
          }, 5000 );
      } 
      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map"></div>
  </body>
</html>

example debug info from console:

remove marker:Object { __gm={...},  gm_accessors_={...},  position=(54.9094444444, -7.289444444440051),  more...}
remove marker:Object { __gm={...},  gm_accessors_={...},  position=(56.306252, -3.2225129999999353),  more...}
remove marker:Object { __gm={...},  gm_accessors_={...},  position=(54.9616666667, -6.9694444444400006),  more...}
lat:56.6022222222, lng:-2.63416666667
lat:56.56138345735925, lng:-2.935781240463257
lat:54.5044444444, lng:-7.35222222222
Sign up to request clarification or add additional context in comments.

5 Comments

i want to add multiple markers according to values in json object. your edited code only show one marker on map.
With a minor change the above works ok - just tested it and it adds markers on every interval
i want to update the previous marker that i have added at start instead of adding marker at every interval
I added map as a parameter to the addmarker function ~ it seemed it wasn't recognising the map object without it
When I initially ran the code in test I wondered why I could not see more markers, even though they were clearly being pulled from the db and output correctly as json - I realised the map was set to a different continent. imgur.com/87UVqjf shows markers added using code ( i'm in scotland ) ~ what do you see in the console with the debug statements??

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.