在JavaScript中为Google地图折线创建位置数组

时间:2017-05-22 07:49:24

标签: javascript arrays google-maps

我想为Google地图API创建一个位置数组,以便在其上绘制多边形线。一切都工作正常,但我的阵列的结构有问题。 Accept数组是:

[
        { lat: 37.772, lng: -122.214 },
        { lat: 21.291, lng: -157.821 },
        { lat: -18.142, lng: 178.431 },
        { lat: -27.467, lng: 153.027 }
        ]

但我生成数组的脚本是:

var routepos= [];  

 $.each(data, function (index, val) {
                            var latlang = val.split(",");
                            routepos.push({
                                lat:  parseFloat( latlang[0]),
                                lng: parseFloat(latlang[1])});

                        })

其中数据来自jj格式成功的ajax请求。

["32.578090,74.080100", "32.578533,74.080100", "32.580070,74.080239", "32.582538,74.080368", "32.583433,74.080443", "32.584554,74.080540"]

我真的错过了什么?或为什么谷歌地图api不接受我的阵列?

1 个答案:

答案 0 :(得分:1)

您错过了jquery链接$.each需要jquery才能运行。您可以看到console.log其展示$未定义



var data =["32.578090,74.080100", "32.578533,74.080100", "32.580070,74.080239", "32.582538,74.080368", "32.583433,74.080443", "32.584554,74.080540"]
 routepos= [];   
 $.each(data, function (index, val) { // $.each statement required jquery
                            var latlang = val.split(",");
                            routepos.push({
                                lat:  parseFloat( latlang[0]),
                                lng: parseFloat(latlang[1])});

                        })
                        console.log(routepos)

<!--This is the jquery link -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

为了更好地使用map而不使用Jquery

&#13;
&#13;
var data =["32.578090,74.080100", "32.578533,74.080100", "32.580070,74.080239", "32.582538,74.080368", "32.583433,74.080443", "32.584554,74.080540"]
var routepos = data.map(a=> ({lat:  parseFloat(a.split(",")[0]), lng: parseFloat(a.split(",")[1])}))
console.log(routepos)
&#13;
&#13;
&#13;