2017-01-25 28 views
-1

我會開始說我對JS比較新,所以請原諒我的無知,如果這是顯而易見的。谷歌地圖api和地理編碼api - 添加標記的問題

我想添加標記到谷歌地圖。我創建了一個數組coordList,然後使用地理編碼API從地址獲取滯後和長時間,並將它們推入coordList。

我現在試圖使用coordList數組來繪製地圖上的標記,但我似乎無法從coordList數組中獲取值。當我運行console.log(typeof coordList) - 它告訴我這是一個對象,但是當我用console.log(coordList)查看數組時,它看起來像一個普通數組?

var coordList = []; 
    var address = []; 

address.push('52+Kalynda+pde,+bohle+plains,+QLD') 
address.push('51+Frank+St,+Kirwan+QLD+4817'); 

    function initMap() { 
    map = new google.maps.Map(document.getElementById('map'), { 
     zoom: 12, 
     center: new google.maps.LatLng(-19.259854,146.8001348), 
     mapTypeId: 'roadmap' 
    }); 


    } 

    function getLatLong(address){ 
    var index; 
    for (index = 0; index < address.length; ++index) { 

    var request = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address[index] + '&key=[MY_key]'; 

    $.getJSON(request, function(data) { 

    var lat = data.results[0].geometry.location.lat; 
    var lng = data.results[0].geometry.location.lng; 

     var coords = []; 
     coords.push(lat); 
     coords.push(lng); 
     //push coords into coordList 
     coordList.push(coords); 

    }); 
    } 
    } 


    // Loop through the results array and place a marker for each 
    // set of coordinates. 
    function addMarkers(coordList) { 

    for (var i = 0; i < coordList.length; i++) { 

     var coords = coordList[i]; 
     var latLng = new google.maps.LatLng(coords[0],coords[1]); 
     var marker = new google.maps.Marker({ 
     position: latLng, 
     map: map 
     }); 
    } 
    } 
    getLatLong(address); 
    addMarkers(coordList); 

回答

1

您的問題是$ .getJSON()是一個異步請求,你的代碼比$ .getJSON之前執行addMarkers()()完成,所以coordList是空的。

您可以在$ .getJSON()回調中添加標記。例如:

var address = []; 

address.push('52+Kalynda+pde,+bohle+plains,+QLD') 
address.push('51+Frank+St,+Kirwan+QLD+4817'); 

function initMap() { 
    map = new google.maps.Map(document.getElementById('map'), { 
     zoom: 12, 
     center: new google.maps.LatLng(-19.259854,146.8001348), 
     mapTypeId: 'roadmap' 
    }); 
} 

function getLatLongAndAddMarkers(address){ 
    var index; 
    for (index = 0; index < address.length; ++index) { 
    var request = 'https://maps.googleapis.com/maps/api/geocode/json?dress=' + address[index] + '&key=[MY_key]'; 
    $.getJSON(request, function(data) { 
     var latLong = new google.maps.LatLng(data.results[0].geometry.location); 
     //add markers here 
     var marker = new google.maps.Marker({ 
      position: latLong, 
      map: map 
     }); 
    }); 
    } 
} 

getLatLongAndAddMarkers(address); 
+0

謝謝堆,現在有道理......正在我的腦海裏! – DGBatch