将json元素添加到变量中

问题描述 投票:-1回答:1

我有一些麻烦。我想配置谷歌地图并从json文件添加点。我想在我的'features'变量中添加'lat'和'lng'(循环'结果'的每个json文件元素),但它不起作用。

json文件

{"act":"success","totalResults":122,"results":[{"id":"1","lat":"50.162292","lng":"-5.089257"},{"id":"2","lat":"50.164001","lng":"-5.069998"},{"id":"3","lat":"50.106697","lng":"-5.549815"},{"id":"4","lat":"50.129349","lng":"-5.515587"},{"id":"5","lat":"50.129333","lng":"-5.515833"},{"id":"6","lat":"50.128429","lng":"-5.519022"},{"id":"7","lat":"50.186115","lng":"-5.421418"},{"id":"8","lat":"50.225258","lng":"-5.274623"},{"id":"9","lat":"50.261471","lng":"-5.067650"}]}

脚本代码

<script>
      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('mapGoogle'), {
          zoom: 7,
          center: new google.maps.LatLng(51.509865, -0.118092),
          mapTypeId: 'roadmap',
          gestureHandling: 'greedy',
          disableDefaultUI: true
        });

        var myjson;
        $.getJSON("http://app.regain-app.com/rest/V1/points/get?lat=50.164001&lng=-5.069998&distance=26", function(json){
            myjson = json;

            console.log(myjson);
        });

        var icons = {
          info: {
            icon: 'http://www.picpng.com/uploads/small/Google_Map_Marker_Red_Peg_77453.Png'
          }
        };

        var features = [
          {
            position: new google.maps.LatLng(50.162292, -5.089257),
            type: 'info'
          }, {
            position: new google.maps.LatLng(50.164001, -5.069998),
            type: 'info'
          }, {
            position: new google.maps.LatLng(50.106697, -5.549815),
            type: 'info'
          }
        ];

        myjson.results.forEach(function(object){

        });

        // Create markers.
        features.forEach(function(feature) {
          var marker = new google.maps.Marker({
            position: feature.position,
            icon: icons[feature.type].icon,
            map: map
          });
        });
      }
    </script>

我将不胜感激任何帮助。 :)

javascript json google-maps
1个回答
0
投票

这里有很多工作要做。

首先,你的循环。你的循环在错误的地方。

var myjson;
        $.getJSON("http://app.regain-app.com/rest/V1/points/get?lat=50.164001&lng=-5.069998&distance=26", function(json){
            myjson = json;

            console.log(myjson);
        });

这是程序设置变量myjson的地方。但是,它只发生在回调中,所以你不能在以后的代码中循环它们,所以把这段代码:

myjson.results.forEach(function(object){

});

在回调内部,并在回调之前声明您的功能变量。

现在在你的forEach循环中:

features.push({
        position: new google.maps.LatLng(parseInt(object.lat), parseInt(object.lng)),
        type: 'info'
      })

push会向数组添加一个新对象,该对象在括号中定义。

© www.soinside.com 2019 - 2024. All rights reserved.