【问题标题】:Send data from .txt file to JavaScript array将数据从 .txt 文件发送到 JavaScript 数组
【发布时间】:2014-05-20 22:03:58
【问题描述】:

我有以下 simple.txt 文件:

new google.maps.LatLng(37.782551, -122.445368)
new google.maps.LatLng(37.754665, -122.403242)
new google.maps.LatLng(37.753837, -122.403172)
new google.maps.LatLng(37.752986, -122.403112)
new google.maps.LatLng(37.751266, -122.403355)

以下 JavaScript 代码:

function initialize() {
  var mapOptions = {
    zoom: 13,
    center: new google.maps.LatLng(37.774546, -122.433523),
    mapTypeId: google.maps.MapTypeId.SATELLITE
  };

  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  var pointArray = new google.maps.MVCArray(taxiData);

  heatmap = new google.maps.visualization.HeatmapLayer({
    data: pointArray
  });

  heatmap.setMap(map);
}

以下数组:

    var taxiData = [ 
    new google.maps.LatLng(37.782551, -122.445368)
    new google.maps.LatLng(37.754665, -122.403242)
    new google.maps.LatLng(37.753837, -122.403172)
    new google.maps.LatLng(37.752986, -122.403112)
    new google.maps.LatLng(37.751266, -122.403355)
];

我想将我的数据从 simple.txt 发送到 JavaScript 中的 taxiData 数组。 我尝试过这样的事情(没有成功):

var taxiData = [
    <?php
    echo file_get_contents("simple.txt");
    ?>
];

你能帮帮我吗?

【问题讨论】:

    标签: javascript php arrays file geolocation


    【解决方案1】:

    您需要用逗号分隔数组元素。你可以在 PHP 中轻松做到这一点:

    <?php echo implode(',', explode('\n', file_get_contents("simple.txt"))); ?>
    

    这只是将文件分解为以换行符分隔的元素数组,然后使用逗号将它们重新连接在一起,从而创建可以毫无问题地传递到 JavaScript 代码中的有效格式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 2022-10-06
      • 1970-01-01
      相关资源
      最近更新 更多