【问题标题】:Gather the Co-Ordinates & Draw them to Google Map收集坐标并将它们绘制到谷歌地图
【发布时间】:2014-06-17 19:05:02
【问题描述】:


我正在尝试从 php 文件中收集几个坐标,并将它们绘制到谷歌地图上,制作几个标记。使用jquery 库的.ajax 方法收集数据。这是我的尝试:

allCoordinates.php:

$db_host = "localhost";
$db_user = "root";
$db_password = "root";
$db_database = "googlemapsdemo";

$connection = new mysqli($db_host, $db_user, $db_password, $db_database);

if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$selectvalue = mysqli_real_escape_string($connection, $_GET['svalue']);

mysqli_select_db($connection, $db_database);

$result = mysqli_query($connection, "SELECT latitude, longitude FROM googlemapsdemo.vtiger_geocoding", MYSQLI_USE_RESULT);

$rows = array();

while ($allCoordinates = mysqli_fetch_array($result)){
    $rows[] = array('latitude' => $allCoordinates[0], 'longitude' => $allCoordinates[1]);
}

$json = json_encode($rows);
print $json;



mysqli_free_result($result);
mysqli_close($connection);

?>

index.php:

<html>
<head>
    <title>Google Maps Demo</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"><script type="text/javascript">

    $(document).ready(function(){
        var coordinates, parsedCoordinates;
        var mapCenter = new google.maps.LatLng(51.508742,-0.120850); //Google map Coordinates
        var map;
        map_initialize(); // load map

        function map_initialize(){

            //Google map option
            var googleMapOptions = 
            { 
                center: mapCenter, // map center
                zoom: 17, //zoom level, 0 = earth view to higher value
                panControl: true, //enable pan Control
                zoomControl: true, //enable zoom control
                zoomControlOptions: {
                style: google.maps.ZoomControlStyle.SMALL //zoom control size
            },
                scaleControl: true, // enable scale control
                mapTypeId: google.maps.MapTypeId.ROADMAP // google map type
            };

            map = new google.maps.Map(document.getElementById("map_container"), googleMapOptions);

            var marker = new google.maps.Marker({
                position: mapCenter,
                map: map
            });

            var infowindow = new google.maps.InfoWindow({
                content:"Hello World!"
            });

            infowindow.open(map,marker);
        }

        $(':submit').on('click', function() { // This event fires when a button is clicked
            $.ajax({ // ajax call starts
                  url: 'allCoordinates.php', // JQuery loads allCoordinates.php
                  dataType: 'json', // Choosing a JSON datatype
                  success: function(data) // Variable data contains the data we get from serverside
                  {
                      alert(data[0].latitude + " " + data[0].longitude);
                      coordinates = data;
                      parsedCoordinates = JSON.parse(coordinates);
                      update(parsedCoordinates);
                  }
            });
            return false; // keeps the page from not refreshing 
        });

        function update(markers){
            var infowindow = new google.maps.InfoWindow(), marker, i;

            google.maps.event.addListener(map, 'center_changed', function(event){
                for (i = 0; i < markers.length; i++) {  
                    marker = new google.maps.Marker({
                        position: new google.maps.LatLng(markers[i].latitude, markers[i].longitude),
                        map: map
                    });

                    google.maps.event.addListener(marker, 'click', (function(marker, i) {

                        return function() {
                            infowindow.setContent(markers[i].latitude + " " + markers[i].longitude);
                            infowindow.open(map, marker);
                        }
                    })(marker, i));
                }
            });
        }

    });

</script>
</head>

<body>
    <div class="container">
        <div id="filters_container">
                <fieldset>
                    <legend>Zona</legend>
                    <form id="submitForm" method="post" action="">
                        <select>.......</select>
                        <button type="submit">Cerca</button>
                    </form>
                </fieldset>

        </div>
        <div id="map_container"></div>
    </div>


</body>
</html>

返回的 JSON 是这样的:

[{"latitude":"45.648110","longitude":"11.497398"},
{"latitude":"45.511180","longitude":"11.511070"},
{"latitude":"45.649630","longitude":"12.304064"},
{"latitude":"45.722110","longitude":"11.435023"},
{"latitude":"45.391083","longitude":"11.276997"},
{"latitude":"45.691465","longitude":"11.483223"},
{"latitude":"45.659787","longitude":"11.795147"},
{"latitude":"45.720608","longitude":"11.453950"},
{"latitude":"45.718757","longitude":"11.333138"},
{"latitude":"45.607387","longitude":"11.497138"},
{"latitude":"46.099075","longitude":"12.160999"},
{"latitude":"45.523017","longitude":"10.152080"},
{"latitude":"45.408520","longitude":"10.838590"},
{"latitude":"45.717608","longitude":"11.462909"},
{"latitude":"45.395371","longitude":"11.274200"},
{"latitude":"45.555142","longitude":"11.543407"},
{"latitude":"45.693428","longitude":"11.446203"},
{"latitude":"44.661260","longitude":"10.886416"},
{"latitude":"45.530448","longitude":"11.499496"},
{"latitude":"45.530448","longitude":"11.499496"},
{"latitude":"22.318567","longitude":"114.179606"},
{"latitude":"45.443304","longitude":"10.952222"},
{"latitude":"45.836699","longitude":"12.014122"},
{"latitude":"45.803245","longitude":"11.355629"},
{"latitude":"45.722110","longitude":"11.435023"},
{"latitude":"45.803245","longitude":"11.355629"},
{"latitude":"45.836699","longitude":"12.014122"},
{"latitude":"45.779430","longitude":"11.429520"},
{"latitude":"45.803245","longitude":"11.355629"}]

问题是没有任何改变;我究竟做错了什么?谢谢!

【问题讨论】:

    标签: javascript php jquery ajax google-maps-api-3


    【解决方案1】:

    我已经解决了。代码如下:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js"></script>
        <script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
        <script type="text/javascript">
    
            $(document).ready(function(){
                var coordinates, parsedCoordinates;
                var map;
                var marker;
                var markers = [];
                var clusterer;
                var bounds = new google.maps.LatLngBounds();
                var coords = new google.maps.LatLng(0, 0);
                var infowindow = new google.maps.InfoWindow();
                map_initialize(); // load map
    
                function map_initialize(){
    
                    //Google map option
                    var googleMapOptions = 
                    {
                        center: coords,
                        zoom: 0, //zoom level, 0 = earth view to higher value
                        panControl: true, //enable pan Control
                        zoomControl: true, //enable zoom control
                        scaleControl: true, // enable scale control
                        mapTypeId: google.maps.MapTypeId.ROADMAP // google map type
                    };
    
                    map = new google.maps.Map(document.getElementById("map_container"), googleMapOptions);
                    //  Fit these bounds to the map
                    map.fitBounds(bounds);
    
                    // Marker Clusterer setup
                    var mcOptions = {
                      gridSize : 50,
                      maxZoom : 15
                    };
    
    
                }
    
                $(':submit').on('click', function() { // This event fires when a button is clicked
    
                    $.ajax({ // ajax call starts
                          url: 'allCoordinates.php', // JQuery loads allCoordinates.php
                          dataType: 'json', // Choosing a JSON datatype
                          success: function(data) // Variable data contains the data we get from serverside
                          {
                              for (i = 0; i < data.length; i++) {
                                bounds.extend(new google.maps.LatLng(data[i].latitude, data[i].longitude));
    
                                marker = new google.maps.Marker({
                                    position: new google.maps.LatLng(data[i].latitude, data[i].longitude),
                                    map: map,
                                    icon: 'http://maps.google.com/mapfiles/ms/icons/red.png'
                                });
    
                                google.maps.event.addListener(marker, 'click', (function(marker, i) {
                                    return function() {
                                        infowindow.setContent("Test");
                                        infowindow.open(map, marker);
                                    }
                                })(marker, i));
    
                                markers.push(marker);
                              }
                              // Fit these bounds to the map
                              map.fitBounds(bounds);
    
                              clusterer = new MarkerClusterer(map, markers);
                          }
                    });
                    return false; // keeps the page from not refreshing 
                });
            });
    
        </script>
    

    【讨论】:

      【解决方案2】:

      我可以看到许多问题:

      1) 您在initialize 中定义map,这意味着没有其他函数可以访问和更新它。在函数之外声明map

      2) 您没有正确访问标记数组;它是一个对象数组,因此您需要使用键来获取数据:

      3) 您需要以不同方式初始化地图(我会为此使用谷歌自己的 window.load 事件)。不要在 jQuery doc.ready 函数中执行此操作。

      4) 当您添加标记时,只有在地图发生变化时才这样做。为什么?去掉那段代码,你的标记就会被添加到地图中。

      这是DEMO

      $(function () {
      
        // code for clicking the button.
      
      });
      
      var map;
      
      function update(markers) {
      
        for (var i = 0; i < markers.length; i++) {
      
          var lat = markers[i].latitude;
          var lng = markers[i].longitude;
      
          var marker = new google.maps.Marker({
            position: new google.maps.LatLng(lat, lng),
            map: map
          });
      
          google.maps.event.addListener(marker, 'click', (function (marker, lat, lng) {
            return function() {
              infowindow.setContent(lat + " " + lng);
              infowindow.open(map, marker);
            }
          })(marker, lat, lng));
      
        }
      
      }
      
      function initialize(markers) {
        // your code
      }
      
      google.maps.event.addDomListener(window, 'load', initialize);
      

      【讨论】:

      • 我不确定这是否是一个好的答案,因为他的代码完全错误。 Ajax 调用在地图创建之前完成。 JSON 输出是一个对象数组,但 update() 需要一个数组数组。所以没有信息窗口内容的数据。
      • 我已经修复了 javascript,但我仍然无法理解我做错了什么,因为我可以收集 JSON 数据,但我无法弄清楚如何将所有坐标绘制到地图中。
      • 我再次更新了我的答案,并为您提供了一个有效的 JSFiddle。
      • ajax 调用一直在检索数据,我怎样才能只检索一次数据?谢谢!
      猜你喜欢
      • 2019-01-23
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-28
      相关资源
      最近更新 更多