使用json对象在地图上添加多个标记

时间:2016-01-21 08:28:41

标签: javascript php jquery json ajax

我的index.php文件如下所示。其中我想使用json对象在其上显示地图和多个标记。此代码仅适用于一个标记。你可以告诉我这个代码如何修改多个标记,如何在$ .ajax()中访问json对象?

<!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>

这是我的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;    
?>

这是我的json对象

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

1 个答案:

答案 0 :(得分:2)

以下未经过测试,但我认为应该可行。有一个函数addmarker,您可以在循环中调用它来处理从ajax调用返回的所有数据。如果每隔几秒钟调用一次,您还需要从地图中清除旧标记 - 因此使用数组存储对每个新标记的引用。

我在与错误处理程序相关的原始代码中发现语法错误 - 不确定我是否以正确的方式更正了因为我不使用jQuery~看起来不错。

<!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>

我在测试中使用的完整代码

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

来自控制台的示例调试信息:

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