javascript - Add multiple markers on map using json object -


my index.php file shown below. in want show map , multiple marker on using json object. code 1 marker. u please tell me how can code modify multiple markers , how can 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);         });         // let's set time interval, let's every 3 seconds check position         setinterval(           function() {             // make ajax call             $.ajax({               datatype: 'json',   // means result (the echo) of server readable javascript object               url: 'final.php',               success: function(data) {                 // return of ajax call.  can use data javascript object                 console.log(data);                 // change position of 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 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 data bus_id= ".$x." order id desc limit 1" ;       $qry_result = mysqli_query($con,$query);// or die(mysqli_error());     // insert new row in table 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 json object

[{"lat":"74.348047","lng":"31.569907"},{"lat":"74.307826","lng":"31.573289"},{"lat":"74.330023","lng":"31.558144"}] 

the following not tested think should work. there function addmarker call in loop process data returned ajax call. if gets called every few seconds need clear old markers map - hence using array store references each new marker.

i found syntax error in original code relating error handler - not sure if have corrected in right way 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 map available in scopes */       var markers=[];/* container store references 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 console, see here */                      console.log( 'lat:%s, lng:%s',lat,lng );                      addmarker.call( this, map, lat, lng, 'hello world - 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 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` 'title',                 `location_map_centre_latitude` 'lat',                 `location_map_centre_longitude` 'lng'              `maps`                  `countryid`=171                  order 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 in scotland, near forfar */       var latlng = { lat: 56.61543329027024, lng: -2.9266123065796137 };       var marker;       var map;       var markers=[];/* container store references 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);         });            /* testing want run few times */         var i=0;         var m=10;           var igm=setinterval(           function() {               /* testing */               i++;               if( > 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 console, see 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 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 

Comments

Popular posts from this blog

SVG stroke-linecap doesn't work for circles in Firefox? -

routes - Laravel 4 Wildcard Routing to Different Controllers -

cross browser - XSLT namespace-alias Not Working in Firefox or Chrome -