Benza
Benza

Reputation: 175

Javascript for loop in map

If you're reading, I have been trying to understand / work out how to do this for days.

I'm using jvectormap and have done everything such as return my users latitude and longitude in an array.

I even have a javascript function that prints the array of each clients latitude and longitude so I know it works.

I just need to somehow include my javascript foreach loop in to my map function.

The following code works but only by manually entering the markers :

<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>

As you can see, the markers are being set manually by me.

I need the markers in there to loop for each users latitude and longitude I get.

I tried revamping the code above to work but I failed. My try looked like this :

<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));

NEW CODE

<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>

Upvotes: 0

Views: 360

Answers (2)

Kosh
Kosh

Reputation: 18393

You can add markers this way:

$.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'}
            })
        })
     }
 });

But I'd rather prepared the correct json on the server-side.

Upvotes: 1

Jeremy Thille
Jeremy Thille

Reputation: 26370

I believe you want to use a function that returns an array :

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

Alternatively, using data_.map() :

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

I have used ES6 because you used the const keyword. For that matter, it should not be const but let, as it's in a loop, so it's variable.

Upvotes: 0

Related Questions