将数据从.txt文件发送到JavaScript数组


Send data from .txt file to JavaScript array

我有以下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.txttaxiData数组在JavaScript。我试过这样做(没有成功):

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

你能帮我吗?

需要用逗号分隔数组元素。这在PHP中很容易做到:

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

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