将制表符分隔文件中的值传递给Google Maps对象

Pass a values from a tab delimited file to Google Maps object

本文关键字:Google Maps 对象 值传 制表符 分隔 文件      更新时间:2024-05-07

我正试图通过printInfo函数将Latitude和Longitude值传递到谷歌地图的对象。我正在加载一个以制表符分隔的文件,我可以毫无问题地从中获取值,但我一直纠结于如何将其传递给initMap函数,以将其提供给中心对象。我应该使用回调函数来传递值吗?如果是这样的话,我不知道该怎么做。我尝试创建一个全局变量,但似乎不起作用。

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。CCD_ 3和地图将以该位置为中心。您甚至可以通过删除addDomListener并在读取csv后调用initMap来推迟映射初始化。将lat/lng参数添加到initMap

有些拼写错误。工作小提琴。