1

I'm trying to use a PHP Array to get long and lat values from a database, and put these onto a map using gmaps.js.

So far, I have created the array in PHP, and echoed this onto my page to confirm the correct values are being displayed.

$data = array();
$data['latitude'] = array($lat);
$data['longitude'] = array($lng);
echo json_encode($data);

So $data is the array, with the values I want inside.

I then want to use jQuery to get the data from json encode, put these into the map marker locations and display the markers like so:

$.ajax({
        type: "POST",
        url: "phppage.php",
        dataType: "JSON",
        success: function(data) {
            $.each(data, function(key, value) {
                poi_marker = {
                     marker: {
                        lat: data.latitude,
                        lng: data.longitude,
                        }
                      } 
                }
                poi_markers.push(poi_marker);
            });

            map.addMarkers(poi_markers);
        }
    });

I get no errors in my console (using firefox and firebug), the map displays but no markers are shown.

2 Answers2

1

I don't think that you're code is actually doing what you think that it is doing. See this fiddle for what is actually happening with your loop.

If you store the array differently on the PHP side, it'll be easier to loop through multiple markers in JS. Also, I don't think gmaps.js needs that extra 'marker' key in the object.

New PHP

$data = array();
$data[] = array(
  'latitude' => $lat
  ,'longitude' => $long
);
echo json_encode($data);

New JS

var poi_markers = []; // make sure you declare this before using it. if you already declare it somewhere else, don't use this line
$.ajax({
    type: "POST",
    url: "phppage.php",
    dataType: "JSON",
    success: function(data) {
        $.each(data, function(key, value) {
            var poi_marker = {
                lat: value.latitude,
                lng: value.longitude
            }
            poi_markers.push(poi_marker);
        });

        map.addMarkers(poi_markers);
    }
});

You might be having trouble because you specify dataType: "JSON" but (atleast in the code you posted) you don't change the header on the php side. You may need to add this line to the top of phppage.php

header("Content-Type: application/json", true);

Where I learned everything I know about gmaps.js

0

I suppose that the data retrieved successfully as needed

$.ajax({
    type: "POST",
    url: "phppage.php",
    dataType: "JSON",
    success: function(data) {
        $.each(data, function(key, value) {
            map.addMarker{
                lat: data.latitude,
                lng: data.longitude
            }
        }  
    }     
});

Check This

Community
  • 1
  • 1
Alaa M. Jaddou
  • 1,180
  • 1
  • 11
  • 30