Google Map API不绘制标记数组

时间:2016-04-20 12:19:39

标签: javascript jquery arrays google-maps google-maps-api-3

我需要一些建议或告知,因为我的代码错了。我是JQuery和google maps api的新手。我有一个JSON来检索我的数据。我已声明一个数组并存储(希望这是正确的方法)。

更新** - 感谢@geocodezip我更新了我的代码以允许正确的数组。

当我运行我的应用程序时,地图加载正常但没有标记。 我已将Google地图的initializeMap()更改为异步版本

function initializeMap() {


        var map = new google.maps.Map(document.getElementById("googleMap"), {
            zoom: 12,
            center: new google.maps.LatLng(citylat, citylng),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });


        var infowindow = new google.maps.InfoWindow();

        var marker, i;

        for (i = 0; i < carparksArray.length; i++) {
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(carparksArray[i][1], carparksArray[i][2]),
                map: map
            });

            google.maps.event.addListener(marker, 'click', (function (marker, i) {
                return function () {
                    infowindow.setContent(carparksArray[i][0]);
                    infowindow.open(map, marker);
                }
            })(marker, i));
        }

    }

My array in console.log image

我现在已经填充了一个数组,但我的地图上仍然没有标记。

这是我的整个脚本。也许存在一些重大缺陷。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 



<script type="text/javascript">
    //define variables
    var geocoder;
    var citylat = 0;
    var citylng = 0;
    var carparksArray = [];

    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
    }
    //Get the latitude and the longitude;
    function successFunction(position)
    {
        var lat = position.coords.latitude;
        var lng = position.coords.longitude;
        codeLatLng(lat, lng)
    }

    function errorFunction()
    {
        alert("Geocoder failed");
    }


    function initialize()
    {
        geocoder = new google.maps.Geocoder();
    }
    //get city of current location and runs codeAddress()
    function codeLatLng(lat, lng) {
        var latlng = new google.maps.LatLng(lat, lng);
        geocoder.geocode({ latLng: latlng }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    var arrAddress = results;
                    console.log(results);
                    $.each(arrAddress, function (i, address_component) {
                        if (address_component.types[0] == "postal_town") {
                            itemPostalTown = address_component.address_components[0].long_name;
                            document.getElementById("town").value = itemPostalTown;
                            codeAddress();



                        }
                    });
                } else {
                    alert("No results found");
                }
            } else {
                alert("Geocoder failed due to: " + status);
            }
        });
    }



    //get latlong of city and runs getCarParks()
    function codeAddress() {
        geocoder = new google.maps.Geocoder();
        var address = document.getElementById("town").value;
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {

                citylat = results[0].geometry.location.lat();
                citylng = results[0].geometry.location.lng();
                getCarParksLatLng();   

            }

            else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
    }
    //sets map up
    function initializeMap() {


        var map = new google.maps.Map(document.getElementById("googleMap"), {
            zoom: 12,
            center: new google.maps.LatLng(citylat, citylng),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });


        var infowindow = new google.maps.InfoWindow();

        var marker, i;

        for (i = 0; i < carparksArray.length; i++) {
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(carparksArray[i][1], carparksArray[i][2]),
                map: map
            });

            google.maps.event.addListener(marker, 'click', (function (marker, i) {
                return function () {
                    infowindow.setContent(carparksArray[i][0]);
                    infowindow.open(map, marker);
                }
            })(marker, i));
        }

    }
    //loads map
    function loadScript() {
        var script = document.createElement("script");
        script.src = "http://maps.googleapis.com/maps/api/js?callback=initializeMap";
        document.body.appendChild(script);
    }

    //get carparks names 
    function getCarParksLatLng() {

        var town = document.getElementById("town").value;
        var carparkList = "<p>";

        var uri = "http://localhost/api/carparks?$filter=Town%20eq%20%27" + town + "%27";
        $.getJSON(uri,
             function (data) {
                 carparksArray = [];
                 $('#here_data').empty(); // Clear existing text.
                 // Loop through the list of carparks.
                 $.each(data, function (key, val) {

                     carparksArray.push([val.Name, val.Latitude, val.Longitude]);

                 });
                 console.log(carparksArray);
             });

        loadScript();
    }
    $(document).ready(initialize)

</script>

2 个答案:

答案 0 :(得分:0)

您没有正确地将条目添加到carparkArray。每个数组元素都需要是一个数组,因此数组如下所示:

var carparksArray = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  // ...
  ];

更新代码:

var carparks = [];
$.getJSON(uri,
   function (data) {
     $('#here_data').empty(); // Clear existing text.
     // Loop through the list of carparks.
     $.each(data, function (key, val) {
        carparks.push([val.Name, val.Latitude, val.Longitude]);
     });
   });
  loadScript();
}

proof of concept fiddle

答案 1 :(得分:0)

感谢大家的帮助。因为@geocodezip说明了这一点 $ .getJSON是异步的我在getJSON函数中移动了我的loadscript()函数调用,它现在绘制了地图点。

mqttConfig :: HostName -> MQTTConfig
mqttConfig host = defaultConfig { cClean = False
                                , cClientID = "myClientId"
                                , cHost = host
                                , cUsername = Just "username"
                                , cPassword = Just "password"
                                , cKeepAlive = Just 10
                                , cReconnPeriod = Just 1
                                , cLogger = stdLogger }