将变量放置在Google地图脚本标记中

时间:2015-11-07 05:49:19

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

我正在尝试将Google方向地图放到我的页面上。 JS元素定义如下。目前这是硬编码的,但我需要将原点(迈阿密,佛罗里达州),目的地(布法罗,纽约州)和航路点变为动态。我使用angular的http.get从后端获取Json的位置字符串。

我的问题如何使原点,目的地和航点成为动态?

<script>
  function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 41.85, lng: -87.65},
    scrollwheel: false,
    zoom: 7
  });

  var directionsDisplay = new google.maps.DirectionsRenderer({
    map: map
  });

  // Set destination, origin and travel mode.
  var request = {
    destination: "Miami, FL",
    origin: "Buffalo, NY",
    travelMode: google.maps.TravelMode.DRIVING,
    waypoints: [
    {
      location:"Richmond, VA",
      stopover:true
    },{
      location:"Washington, DC",
      stopover:true
    }],
};

var directionsService = new google.maps.DirectionsService();

directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
  directionsDisplay.setDirections(response);
  }
 });
}
</script>

1 个答案:

答案 0 :(得分:0)

以下是JSON数组的示例。在这个例子中,数组是在js作用域中声明的,但是你应该以不同的方式访问你的数组,我假设使用ajax。无论如何,您将根据需要安排其余的代码。

数组声明:

var placesJSON = 
  [   
 {
     "location":"Richmond, VA",
      stopover:true

 },
  {
      "location":"Washington, DC",
      "stopover":true

  },
  {
      "location":"Atlanta",
      "stopover":true

  }
  ];

动态变量:

var request = {
    destination: "Miami, FL",
    origin: "Buffalo, NY",
    travelMode: google.maps.TravelMode.DRIVING,
    waypoints: [
    {
      location:placesJSON[0].location,
      stopover:placesJSON[0].stopover
    },{
      location:placesJSON[2].location,
      stopover:placesJSON[2].stopover
    }],
};

这是小提琴的例子: https://jsfiddle.net/eugensunic/45n45cpd/1/

如果要按特定名称(而不是索引)访问JSON数组。然后我建议循环一个数组并创建一个if语句,例如

if(desired_destination== placesJSON[index].location){// select this places} 

确认您的请求。