簡體   English   中英

將制表符分隔文件中的值傳遞給Google Maps對象

[英]Pass a values from a tab delimited file to Google Maps object

我正在嘗試從printInfo函數將緯度和經度值傳遞到Google地圖的對象。 我正在加載制表符分隔的文件,並且可以毫無問題地從中獲取值,但是我在如何將其傳遞給initMap函數以將其傳遞給中心對象方面陷入了困境。 我應該使用回調函數來傳遞值嗎? 如果是這樣,我不是100%如何做到這一點。 我嘗試創建一個Global變量,但是它似乎沒有用。

function initMap() {
    var mapDiv = document.getElementById('map');
    var mapProp =  {
      center: {lat: 44.540, lng: -78.546},
      zoom: 8
    };
    var map = new google.maps.Map(mapDiv,mapProp);
  }
  google.maps.event.addDomListener(window,'load',initMap);


//Load in tab delimited file
d3.text("ix_cities.tmpl", function(text){

    printInfo(text);
 });


//print out the info in the console
//I'm trying to pass the Lat/Long values to the google map API
function printInfo(text) {
   var info = d3.tsv.parseRows(text);
    console.log(info);

    var infoLen = info.length;

    console.log("Cities file Length: " + infoLen);

    for(var i = 0; i < infoLen; i++ ){

        console.log("Title: " + info[i][0]);
        console.log("Street Address: " + info[i][1]);
        console.log("City & ZIP: " + info[i][2]);
        console.log("Phone Number: " + info[i][3]);
        console.log("Lat: "  + info[i][4]);
        console.log("Long: " + info[i][5]);
        console.log("URL: " + info[i][6]);
    } 



}

全局變量不好。 使用命名空間。

(function(myMaps) {    
    var map;
    google.maps.event.addDomListener(window, 'load', initMap);
    myMaps.initMap = function() {
        var mapDiv = document.getElementById('map');
        var mapProp = {
            center: { lat: 44.540, lng: -78.546 },
            zoom: 8
        };
        map = new google.maps.Map(mapDiv, mapProp);
    }
    myMaps.center = function(lat, lng) {
        map.setCenter(new google.maps.LatLng(lat, lng));
    }
}(window.myMaps = window.myMaps || {}));

現在,從js中的其他任何地方調用myMaps.center 通過Latitude Longitude和地圖將以該位置為中心。 您甚至可以通過刪除addDomListener並在讀取csv后調用initMap來推遲地圖初始化。 lat/lng參數添加到initMap

一些錯字。 工作提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM