Search code examples
javascriptjquerygoogle-maps-api-3ruby-on-rails-3.1

Google Maps V3 - json marker loading issue (using Rails 3.1 for data)


We're building a google map app in rails that initially loads some makers using a javascript json marker generating function (using the rails .to_json method on the data object).

Then we have a listener on the zoom action that hoovers the new json file directly and feeds it into the same marker function above.

On initial load the markers turn up fine, but on zoom no new ones seem to be showing up. Checking in the rails logs, the json file is being called, so the problem is either to do with how that json data is processed, or how the markers are delivered.

Can any of you see what the problem is?

    var map;
    function initialize() {
      var myOptions = {
        zoom: <%= @zoom %>,
        center: new google.maps.LatLng(<%= @centre %>),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }; 

      map = new google.maps.Map(document.getElementById('map_canvas'),
          myOptions);

      stream_json = (<%= raw(@stream.to_json) %>);
      parse_json(stream_json); 

      google.maps.event.addListener(map, 'zoom_changed', function() {
        json_url = "/test?bounds="+map.getBounds()+"&zoom="+map.getZoom();
        stream_json = $.getJSON(json_url);
        parse_json(stream_json);
      });

      function parse_json(json) {
        if (json.length > 0) { 
          var markers = [];
          for (i=0; i<json.length; i++) {
            var place = json[i];
            alert(place.longitude +','+place.latitude);
            // addLocation(place);
            markers[i] = new google.maps.Marker({
              map: map,
              position: new google.maps.LatLng(place.latitude, place.longitude)
            });
          }
        }
      };

    }

    google.maps.event.addDomListener(window, 'load', initialize);

Many thanks in advance for any pointers you can send our way!


Solution

  • You're not using getJSON correctly. It's an asynchronous call, so you need to supply a callback:

      google.maps.event.addListener(map, 'zoom_changed', function() {
        json_url = "/test?bounds="+map.getBounds()+"&zoom="+map.getZoom();
        $.getJSON(json_url, function(data) {
          parse_json(data);
        });
      });