显示多个标记,变量和数组问题

时间:2015-10-02 21:09:23

标签: javascript php google-maps google-maps-api-3

我尝试在地图上显示多个标记。我把adata属性中的倍数位置放在我的php文件中。然后我尝试在我的javascript中获取这些信息。

如果我直接粘贴坐标,则会出现标记。如果我引用他们不知道的数据属性。 (唯一的区别在于以开头的。)

此代码有效:

function GoogleMapsInit(){
setTimeout(function initialize() {
    var emplacements = $('#iframecarte').attr("data-emplacements");
    // Emplacements returns [[45.5314817,-73.1835154], [45.570004,-73.448701] ]
    var mapOptions = {
        zoom: 12,
        center: new google.maps.LatLng(45.5580421, -73.7303025)
    };
    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    var locations = [[45.5314817,-73.1835154], [45.570004,-73.448701] ];

    var marker, i;
    var markers = new Array();

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][0], locations[i][1]),
        map: map
      });

      markers.push(marker);

    }

}, 500);
}

这个没有:

function GoogleMapsInit(){
setTimeout(function initialize() {
    var emplacements = $('#iframecarte').attr("data-emplacements");
    // Emplacements returns [[45.5314817,-73.1835154], [45.570004,-73.448701] ]
    var mapOptions = {
        zoom: 12,
        center: new google.maps.LatLng(45.5580421, -73.7303025)
    };
    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    var locations = emplacements;

    var marker, i;
    var markers = new Array();

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][0], locations[i][1]),
        map: map
      });

      markers.push(marker);

    }

}, 500);
}

变量位置在引用安置变量时有什么问题,以便标记不显示?

1 个答案:

答案 0 :(得分:1)

非工作版本的安置是一个字符串,而不是一个数组。

将字符串转换为javascript数组:

SELECT LPAD(branch, 2, '0') AS branch
FROM (
    SELECT DISTINCT branch FROM company1 
    UNION 
    SELECT DISTINCT branch FROM company2
) AS x

proof of concept fiddle

代码段

&#13;
&#13;
var locations = JSON.parse(emplacements);
&#13;
function GoogleMapsInit() {
  setTimeout(function initialize() {
    var emplacements = $('#iframecarte').attr("data-emplacements");
    // Emplacements returns [[45.5314817,-73.1835154], [45.570004,-73.448701] ]
    var mapOptions = {
      zoom: 9,
      center: new google.maps.LatLng(45.5580421, -73.7303025)
    };
    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    var locations = JSON.parse(emplacements);

    var marker, i;
    var markers = new Array();

    for (i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][0], locations[i][1]),
        map: map
      });

      markers.push(marker);

    }

  }, 500);
}
GoogleMapsInit();
&#13;
html,
body,
#map-canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
&#13;
&#13;
&#13;