【问题标题】:Javascript for loop in map地图中的 Javascript for 循环
【发布时间】:2017-07-10 14:35:40
【问题描述】:

如果您正在阅读,我几天来一直在尝试理解/弄清楚如何做到这一点。

我正在使用 jvectormap 并已完成所有操作,例如在数组中返回我的用户纬度和经度。

我什至有一个 javascript 函数,可以打印每个客户端的纬度和经度数组,所以我知道它可以工作。

我只需要以某种方式将我的 javascript foreach 循环包含到我的地图函数中。

以下代码有效,但只能通过手动输入标记:

<script>
$.ajax({
    url: "includes/get_dash_map.php",
    context: document.body,
    type: 'POST',
    data: {get_data_:true},
    success: function(value_) {
        const data_ = JSON.parse(value_);
        const $parent = $('#all-the-coordinates');

        for(const row of data_){
            //const $element = $('<span></span>');
            //$element.text(`${row['client_latitude']}, ${row['client_longitude']}, `);
            //$parent.append($element);
        }

        $('#map').vectorMap({
            map: 'world_mill_en',
            backgroundColor: 'transparent',
            zoomOnScroll: false,
            hoverOpacity: 0.7,
            markerStyle: { initial: { fill: '#F8E23B', stroke: '#383f47' } },
            markers: [
                {latLng: ['51.5605', '0.4524'], name: 'BenzaHdd'},
            ]
        })
}})
</script>

如您所见,标记是由我手动设置的。

我需要那里的标记来循环我得到的每个用户的纬度和经度。

我尝试修改上面的代码以使其正常工作,但失败了。我的尝试看起来像这样:

<script>
$.ajax({
    url: "includes/get_dash_map.php",
    context: document.body,
    type: 'POST',
    data: {get_data_:true},
    success: function(value_) {
        const data_ = JSON.parse(value_);
        const $parent = $('#all-the-coordinates');

        $('#map').vectorMap({
            map: 'world_mill_en',
            backgroundColor: 'transparent',
            zoomOnScroll: false,
            hoverOpacity: 0.7,
            markerStyle: { initial: { fill: '#F8E23B', stroke: '#383f47' } },

            for(const row of data_) {
            //const $element = $('<span></span>');
            //$element.text(`${row['client_latitude']}, ${row['client_longitude']}, `);
            //$parent.append($element);
            markers: [ { latLng: [`${row['client_latitude']}, ${row['client_longitude']}`], name: 'Benza' } ],

            },
        })
}})
</script>

get_dash_map.php

    $user_grab = mysqli_query($con, "SELECT * FROM users");


    while ($users_ = mysqli_fetch_array($user_grab)) {
        $client_ip = $users_['ip'];

        //This is for getting each users location on our map
        $ip               = $client_ip;
        $geocode          = 
        file_get_contents("http://freegeoip.net/json/{$ip}");
        $output           = json_decode($geocode);
        $client_latitude  = $output->latitude;
        $client_longitude = $output->longitude;

        $response_[] = [$client_latitude, $client_longitude];            
    }

    echo str_replace(array('[', ']'), '', htmlspecialchars(json_encode($response_), ENT_NOQUOTES));

新代码

<script>
function fetchMap() {
$.ajax({
url: "includes/get_dash_map.php",
context: document.body,
type: 'POST',
data: {get_data:true},
success: function(value) {

    $('#map').vectorMap({
        map: 'world_mill_en',
        backgroundColor: 'transparent',
        zoomOnScroll: false,
        hoverOpacity: 0.7,
        markerStyle: { initial: { fill: '#F8E23B', stroke: '#383f47' } },
        markers: () => value.map(row =>{ return {latLng: [`${row['0']},${row['1']}`], name: `${row['0']}`}})
        //markers: [
        //    {latLng: ['51.5605', '0.4524'], name: 'BenzaHdd'},
        //]
    })
   },
});
}
$(document).ready(function() { fetchMap(); });
</script>

【问题讨论】:

  • 您能否向我们展示一个您从调用 includes/get_dash_map.php 得到的 JSON 示例 - console.log(data_ ) 应该这样做
  • @Jamiec 当我使用修改后的代码时,我什么也得不到。它不显示地图。它甚至没有显示来自 get_dash_map 的请求。
  • 我认为你误会了我。直接在const data_ = JSON.parse(value_); 行之后,如果您输入console.log(data_),您会在控制台中看到任何内容吗?
  • @Jamiec 哦,好吧。不,我什么都没看到。
  • 那么您的问题不在于您的地图,而在于您的 ajax 请求!在您取回某些东西之前,您所做的任何事情都不会在地图上显示任何内容。

标签: javascript loops foreach jvectormap


【解决方案1】:

您可以通过这种方式添加标记:

$.ajax({
    url: "includes/get_dash_map.php",
    context: document.body,
    type: 'POST',
    data: {get_data_:true},
    dataType: 'json',
    success: function(data_) {
        const $parent = $('#all-the-coordinates');

        $('#map').vectorMap({
            map: 'world_mill_en',
            backgroundColor: 'transparent',
            zoomOnScroll: false,
            hoverOpacity: 0.7,
            markerStyle: { initial: { fill: '#F8E23B', stroke: '#383f47' } },
            markers: data_.map(function(row){
                 return {latLng: [row[0], row[1]], name: 'Ben'}
            })
        })
     }
 });

但我宁愿在服务器端准备正确的 json。

【讨论】:

  • 我正在使用这个:pastebin.com/P5VFiuLM,但它仍然没有显示地图。
  • 我刚刚意识到,当我进入我的 get_dash_map 页面时,它回显了 client_latitude[values here] 和 longitude[values here],这会破坏地图,因为它只想读取值,而不是字符串。现在我已经做到了,它有一个最终的 [ ]。我刚刚删除了这些方括号,现在我看到了这个Image here 任何想法为什么我的地图仍然没有显示? I'm using this
  • @Ben,请将includes/get_dash_map.php 的回复添加到您的问题中。看起来我们解析不正确。从你的问题我猜我一定是这样的:[{client_latitude: 23.456, client_longitude:-76.456, name:'Ben'}, {client_latitude: 25.456, client_longitude:-80.456, name:'Jack'}, {client_latitude: 26.456, client_longitude:-99.456, name:'Charlie'}, ...]
  • 没有。当我打印 client_latitude 和 client_longitude 时,它​​会全部显示出来
  • 这仍然没有显示我的地图。我的值是否应该返回Like this
【解决方案2】:

我相信你想使用一个返回数组的函数:

$('#map').vectorMap({
     markers: () => {
         let markers_array = [];
         for(let row of data_) {
              markers_array.push( {latLng... } )  // Make your loop here
          }
          return markers_array;
     }
})

或者,使用data_.map()

$('#map').vectorMap({
     markers: () => data_.map( row => {
          return { row.latLng... } // Make your loop here
     })
})

我使用 ES6 是因为你使用了 const 关键字。就此而言,它不应该是const,而是let,因为它处于循环中,所以它是可变的。

【讨论】:

  • 我没有什么?
  • 我刚试过你的版本 - pastebin.com/mVYVjgiE 但地图仍然没有显示出来。
  • 我刚刚意识到,当我进入我的 get_dash_map 页面时,它回显了 client_latitude[values here] 和 longitude[values here],这会破坏地图,因为它只想读取值,而不是字符串。现在我已经做到了,它有一个最终的 [ ] 围绕值。我怎么能删除这些? Image Proof Here
  • 呃,我不知道,不看你的代码很难盲目回答。此外,这是另一个问题,所以应该作为一个新问题提出。
猜你喜欢
  • 1970-01-01
  • 2019-05-12
  • 1970-01-01
  • 1970-01-01
  • 2011-10-27
  • 2011-03-13
  • 2018-03-09
  • 2015-02-25
  • 2015-09-18
相关资源
最近更新 更多