简体   繁体   中英

Send data from .txt file to JavaScript array

I have following simple.txt file:

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)

following JavaScript code:

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);
}

and following array:

    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)
];

I would like to send my data from simple.txt to taxiData array in JavaScript. I have tried something like this (without success):

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

Can you help me?

You need to separate the array elements with commas. You can do that easily enough in PHP:

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

That simply breaks the file into an array of newline-delimited elements, then joins them back together using commas, creating a valid format that can be passed into the JavaScript code without issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM