TAGS :Viewed: 14 - Published at: a few seconds ago

[ Gmaps4rails - Map throwing JS error on first load when JSON == "[]" ]

I am using the geocoder gem's .nearby method to query my DB and return nearby location objects.

Question 1: When loading the map for the first time, no markers are passed to the JS, and it does not load the map. How can I fix this issue without loading a marker?

<script type="text/javascript">
Gmaps.map = new Gmaps4RailsGoogle();
Gmaps.load_map = function() {
Gmaps.map.map_options.detect_location = true;
Gmaps.map.map_options.center_on_user = true;
Gmaps.map.initialize();
Gmaps.map.markers = ; // BLOWS UP HERE
Gmaps.map.markers_conf.list_container = "markers_list";
Gmaps.map.create_markers();
Gmaps.map.adjustMapToBounds();
Gmaps.map.callback();
};
Gmaps.oldOnload = window.onload;
 window.onload = function() { Gmaps.triggerOldOnload(); Gmaps.loadMaps(); };
</script>`

Question 2: When user searches and no nearby results are available to their search, how to recover from this just showing a random location (right now it loads the middle of the ocean).

Question 3: When user searches and no nearby results are available, can I show nearby locations to their current location using browser geolocation (I know it's not supported in all browsers).

Answer 1


Answer 1:

There is no bug in the gem.

This line of yours makes javascript cry:

@json = nil

Indeed nil isn't valid json.

You should do:

@json = [].to_json

Answer 2

If your query doesn't return anything, Make another one to get a random object. Can't see any problem there.

Answer 3

Geolocation from browser is included in the gem, you even have a callback on success. See code. But you'll have to write your own javascript fitting your own logic.