0

I am trying to make an AJAX map Google map, where the place markers update but not the map.

I have an ajax setup with a settimeout function, which returns new javascript. When the new javascript is loaded into my HTML, the changes do not reflect on my google map.

When I go into the firefox inspector and try and manipulate the javascript, (to try and change marker GPS coordinates), nothing happens to the map, and the points are still the same. Why does that not affect the map?

I have looked at several links to try and help me, but none of them explain the logic behind the javascript.

My PHP script returns javascript in plain text. But when these get added to the HTML, The google map does not change and looks like it needs to be re initialized before it recognizes new javascript?

Can someone explain how I should update the javascript, so the map re-centers on the newest marker and places the newest marker without refreshing the page / re initializing the map?

 <div id="map"></div>
<script>

  function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
     zoom: 13,
      center: {lat:  -20.530637, lng: 46.450046}
    });

    // Create an array of alphabetical characters used to label the markers.
    var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

    // Add some markers to the map.
    // Note: The code uses the JavaScript Array.prototype.map() method to
    // create an array of markers based on a given "locations" array.
    // The map() method here has nothing to do with the Google Maps API.
    var markers = locations.map(function(location, i) {
      return new google.maps.Marker({
        position: location,
        label: labels[i % labels.length]
      });
    });

    // Add a marker clusterer to manage the markers.
    var markerCluster = new MarkerClusterer(map, markers,
        {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
  }
  var locations = [
      new google.maps.LatLng("-21.530637,46.450046),          
      new google.maps.LatLng("-22.530637,46.450046),

  ]
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<div class="result"></div>

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    function refresh_div() {
        jQuery.ajax({
            url:'content.php',
            type:'POST',
            success:function(results) {
                locations=results;

                jQuery(".result").html(results);
            }
        });
    }

    t = setInterval(refresh_div,5000);
</script>

My "content.php" file. returns more google maps LatLng markers in plain text.

so PHP output is:

new google.maps.LatLng("-23.530637,46.450046"),
new google.maps.LatLng("-24.530637,46.450046"),
new google.maps.LatLng("-25.530637,46.450046"),
new google.maps.LatLng("-26.530637,46.450046")
gunter
  • 139
  • 5

2 Answers2

1

I would like to summary the behavior of your ajax map:

  • Initialize map (probably with a set of predefined locations)
  • Repeatedly call content.php to retrieve new update of markers
  • Draw new markers to your map

The problem is that your code that handles ajax result doesn't do any map manipulation. In fact, it has to update the variable locations with new location set. Then create new markers with updated list of locations, then call MarkerCluster to apply them. I created a fiddle to demonstrate it: https://jsfiddle.net/anhhnt/paffzadz/1/ What I did is extract the marker creating part from initMap, so that it can be called multiple times after locations is updated.

function updateMarker () {
  // Create an array of alphabetical characters used to label the markers.
  var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

  // Add some markers to the map.
  // Note: The code uses the JavaScript Array.prototype.map() method to
  // create an array of markers based on a given "locations" array.
  // The map() method here has nothing to do with the Google Maps API.
  var markers = locations.map(function(location, i) {
    return new google.maps.Marker({
    position: location,
    label: labels[i % labels.length]
  });
});

// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
  {imagePath:     'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
};
function initMap() {

  window.map = new google.maps.Map(document.getElementById('map'), {
    zoom: 3,
    center: {lat: -28.024, lng: 140.887}
  });
  updateMarker(map);
};
var locations = [
  {lat: -31.563910, lng: 147.154312},
  {lat: -33.718234, lng: 150.363181},
  {lat: -33.727111, lng: 150.371124}
]
function refresh_div() {
  jQuery.ajax({
  url:'/echo/json/',
  type:'POST',
  data: {
  json: JSON.stringify([
    {lat: -42.735258, lng: 147.438000},
    {lat: -43.999792, lng: 170.463352}
   ])
  },
 success:function(results) {
  locations.concat(results);
  updateMarker();
 }
});
}

t = setInterval(refresh_div,5000);

Hope it helps.

ntahoang
  • 441
  • 5
  • 17
  • Thank you so much for your reply. For the refresh_div() function, Would my PHP need to output a JSON? – gunter Nov 26 '16 at 12:11
  • I would also like to note, your fiddle doesn't display anything. – gunter Nov 26 '16 at 12:15
  • You can you any format you want, as long as your JavaScript code can understand and update the `result` to `locations`. However, JSON is recommended for the simplicity and standard – ntahoang Nov 26 '16 at 12:16
  • I'm not sure why you can't see the fiddle, it's still displaying well for me. – ntahoang Nov 26 '16 at 12:19
  • Sorry, I am a little confused hope you dont mind. Where do I retrieve the data my PHP file sent? Is it possible to just apply the php output without using JSON.stringify? – gunter Nov 26 '16 at 12:25
  • I would like to be able to simply output my PHP results (lat,long) into it. – gunter Nov 26 '16 at 12:25
  • I ran your fiddle, but is it possible to get the map to recenter on the latest marker? I have GPS data that gets updated in a SQL database, and I would like to see the live updates – gunter Nov 26 '16 at 12:27
  • Yes, it is possible, a Google search might give what you need. Try this http://stackoverflow.com/questions/6150409/google-map-v3-set-center-to-specific-marker – ntahoang Nov 26 '16 at 12:33
  • Okay thanks. But is there anyway you can help me with the PHP output to the javascript? If I return a JSON what does the structure need to look like? array("data"=>array(array("lat"=>xxxx,"lon"=>yyyyy),array("lat"=>xxxx,"lon"=>yyyyy),array("lat"=>xxxx,"lon"=>yyyyy)))); – gunter Nov 26 '16 at 12:38
  • Okay, lets say the output is JSON encoded. Would I remove the json: JSON,stringify? – gunter Nov 26 '16 at 12:55
  • The piece of code around JSON.stringify is just only for demostration inside jsfiddle, remove it completely in your code :) – ntahoang Nov 26 '16 at 12:57
  • Thank you so much for your patience and assistance. Would the "results" in the "success:function(results)" be my PHP output, in a JSON? (an array, of arrays, of lat,long)? Also, when I tried your fiddle code, and replaced in my API key, it didn't work, no placemarkers loaded. Any reason why this might be? – gunter Nov 26 '16 at 13:01
  • Sorry I cannot answer everything in a single question. Please debug yourself and post other question if you cannot solve them – ntahoang Nov 26 '16 at 15:53
0

Perhaps you have simple syntax error in your code - missing closing double quote:

 new google.maps.LatLng("-23.530637,46.450046"),
 ...

..or better - remove first double quote:

new google.maps.LatLng(-23.530637,46.450046),
 ...
Bud Damyanov
  • 30,171
  • 6
  • 44
  • 52
  • No, it doesn't have to do with that. unfortunately. I have tried simply printing the PHP script into the locations marker. And they all print out and display on the map fine. The problem is when I go and use the inspector to adjust the javascript, no changes reflect. Perhaps the map needs to be re initialized? – gunter Nov 26 '16 at 11:23
  • The quotes was a error on my part when I put it on SO – gunter Nov 26 '16 at 11:25
  • When I use AJAX to update the locations markers, I can see them in the javascript, but no changes on the map. – gunter Nov 26 '16 at 11:27