标记没有加载到地图上,但数据来自location.php

时间:2017-03-30 09:06:39

标签: javascript php ajax

    <?php
    error_reporting(E_ALL ^ E_DEPRECATED);

    $conn = mysql_connect("localhost", "root", "root") or die(mysql_error());
    mysql_select_db("db_jawandsons") or die(mysql_error());


    ?>

    <html>
    <head>
     <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <title>Google Maps</title>

    <!-------- Customizable Css for Map  ----------------------------->
        <style type="text/css">
            body { font: normal 10pt Helvetica, Arial; }
            #map { width: 1200px; height: 500px; border: 0px; padding: 0px; }
        </style>

        <!---------------- Java Scripts for Map  ----------------->
        <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
        <!------------- Java Scripts for Map  ------------------->
        <script type="text/javascript">
    var marker;
    var map = null;
    var markersArray = [];

        //--------------------- Sample code written by vIr ------------
        var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png",
                   new google.maps.Size(32, 32), new google.maps.Point(0, 0),
                   new google.maps.Point(16, 32));
                        var center = null;

                        var currentPopup;
                        var bounds = new google.maps.LatLngBounds();
                        function addMarker(lat, lng, info) {
                            var pt = new google.maps.LatLng(lat, lng);
                            bounds.extend(pt);
                                marker = new google.maps.Marker({
                                position: pt,
                                draggable: true,
                                raiseOnDrag: true,
                                icon: icon,
                                map: map
                            });
                             markersArray.push(marker);
                            var popup = new google.maps.InfoWindow({
                                content: info,
                                maxWidth: 300
                            });
                            google.maps.event.addListener(marker, "click", function() {
                                if (currentPopup != null) {
                                    currentPopup.close();
                                    currentPopup = null;
                                }
                                popup.open(map, marker);
                                currentPopup = popup;
                            });
                            google.maps.event.addListener(popup, "closeclick", function() {
                                map.panTo(center);
                                currentPopup = null;
                            });
                        }

                        function initMap() {
                            map = new google.maps.Map(document.getElementById("map"), {

                                center: new google.maps.LatLng(0, 0),
                                zoom: 14,
                                mapTypeId: google.maps.MapTypeId.ROADMAP,
                                mapTypeControl: true,
                                mapTypeControlOptions: {
                                    style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
                                },
                                navigationControl: true,
                                navigationControlOptions: {
                                    style: google.maps.NavigationControlStyle.ZOOM_PAN
                                }
                            });


      setInterval(function mapload(){

                    $.ajax({
                                type: "POST", 
                                url: 'location.php',
                               // data: form_data,
                                success: function(data)
                                {
                                //  alert(data);
                               // var json_obj = $.parseJSON(data);//parse JSON
                                    var json_obj = jQuery.parseJSON(JSON.stringify(data));
                                    for (var i in json_obj) 
                                    {   addMarker(json_obj[i].u_lat, json_obj[i].u_lon,"Longitude:" + json_obj[i].u_lon + "<br>" + json_obj[i].u_email + "<br>" + json_obj[i].u_name);

                                    }
                                },
                                dataType: "json"//set to JSON    
                            })    


      },3000);

       center = bounds.getCenter();
       map.fitBounds(bounds);

       }


        setInterval(function removeMarker() {
        if (markersArray) {
            for (i=0; i < markersArray.length; i++) {
                markersArray[i].setMap(null);
                 marker=null;
            }
        markersArray.length = 0;
        }
    },3000);
       </script>

      </head>
        <body onLoad="initMap()" style="margin:0px; border:0px; padding:0px;">
           <div id="map"></div>
        </body>
     </html>


It does not add markers to the map.how can i add markers to the map. please anyone tell me where is the problem is, thank in advance :)

<?php

$conn = mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("db_jawandsons") or die(mysql_error());


$return_arr = array();
$data=array();
$result = mysql_query("SELECT lat,lng,vname,speed FROM v_data where sno='1'")or die(mysql_error());
  while ($row = mysql_fetch_assoc($result)) {
    $data[] = $row['lat'];
    $data[] = $row['lng'];
    $data[] = $row['vname'];
    $data[] = $row['speed'];
    //array_push($return_arr,$data);
}

echo json_encode($data);

   //echo("addMarker(30.91995, 75.93287, '<b>$name</b><br />$desc');\n");
?>

我想将我的位置添加到地图中,它会动态显示。如何在地图上添加多个位置或单个位置(lat,lon)。

让我知道php代码是否有问题。如何在没有页面重新映射的情况下重新加载地图。我尝试了很多脚本,但没有为我工作。请帮帮我。

1 个答案:

答案 0 :(得分:0)

这对我有用。我有这个嵌入了PHP的html页面。也许你可以尝试在这里查看并获得你需要的东西。

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA0XjHka3iMTH5jEuy-bYPWNZdILVOQsWI&callback=initMap"></script>
    <script>
      function initialize() {

        var markers = [];
        var mapCanvas = document.getElementById('map-canvas');
        //San Pablo City
        var myLatlng = new google.maps.LatLng(14.0667, 121.3333);
        <?php
            if (isset($_GET['latitude']) && $_GET['latitude'] != '' && isset($_GET['longitude']) && $_GET['longitude'] != ''){
              ?>
              myLatlng = new google.maps.LatLng(<?=$_GET['latitude']?>, <?=$_GET['longitude']?>);

         <?php   } ?>

        var mapOptions = {
          center: myLatlng,
          zoom: 17,
           mapTypeControlOptions: {
           mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE,google.maps.MapTypeId.HYBRID]
        },
          mapTypeId: google.maps.MapTypeId.NORMAL
        }

        var map = new google.maps.Map(mapCanvas, mapOptions);

         map.setTilt(45);


        var infowindow = new google.maps.InfoWindow({

           maxWidth: 400

        });


         <?php foreach($crimes as $crime) {  

            if ($crime['latitude'] != null AND $crime['longitude'] != '') { 

            $content = "<b>Date : ". date('M d Y',strtotime($crime['date_crime']))."</b><br>";
            $content .= "<p>". $crime['useful_info']."</p>";

            ?>

            addMarker( new google.maps.LatLng(<?=$crime['latitude']?>,<?=$crime['longitude']?>), '<?=$crime['sub_category']?>','<?=str_replace('#','',$crime['color'])?>','<?=substr($crime['sub_category'],0,1)?>',<?=$crime['complaint_id']?>,<?=esc($content)?>);


         <?php  } } ?>

         addListener();

        // Add a marker to the map and push to the array.
        function addMarker(location,title,color,letter,id,content) {

          var pinColor = color;
        var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=" + letter + "|" + pinColor,
                      new google.maps.Size(21, 34),
                      new google.maps.Point(0,0),
                      new google.maps.Point(10, 34));

          var marker = new google.maps.Marker({
            position: location,
            map: map,
            title : title,
            animation: google.maps.Animation.DROP,
            icon: pinImage

          });
          marker.set("id",id);
          marker.set("content",content);

          markers.push(marker);
        }

        function getMessage(title,str){
          var ret =  '<div id="content">'+
              '<div id="siteNotice">'+
              '</div>'+
              '<h4 id="firstHeading" class="firstHeading">' + title + '</h1>'+
              '<div id="bodyContent">'+ str +

               '</div>'+
              '</div>';
              return ret;
        }

        // Sets the map on all markers in the array.
        function setAllMap(map) {
          for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(map);
          }
        }

        // Removes the markers from the map, but keeps them in the array.
        function clearMarkers() {
          setAllMap(null);
        }

        // Shows any markers currently in the array.
        function showMarkers() {
          setAllMap(map);
        }

        // Deletes all markers in the array by removing references to them.
        function deleteMarkers() {
          clearMarkers();
          markers = [];
        }

       function addListener(){
          for (var i = 0; i < markers.length; i++) {
              google.maps.event.addListener(markers[i], 'click', function () {
               // do something with this marker ...
                var id = this.get("id");
                  infowindow.setContent(getMessage(this.getTitle(),this.get("content")));
                  infowindow.setPosition(this.getPosition());
                  infowindow.open(map,markers[i]);
              });

           }
        }

        //google.maps.event.addListener(marker, 'click', function() {
          //  map.setZoom(8);
          //  map.setCenter(marker.getPosition());
       // });

      } 

      google.maps.event.addDomListener(window, 'load', initialize);


    </script>
<div class="page-header">
  <h3>Report > <small>Map View</small></h2>
</div>

    <div class = "col-md-10">
             <div id="map-canvas"></div>
     </div>