Google Maps - Setting It Up To Work With Rails 5 - Geocoder Not Geocoding
Solution 1:
As usual, start simple and slowly add more code. I used the basic Rails app from my previous answer.
I added gem 'geocoder'
to Gemfile.
After bundle install
, I added
geocoded_by :name# can also be an IP address
after_validation :geocode
to my Marker class, which already has latitude and longitude defined as :decimal attributes.
In rails c
:
Marker.create(:name =>'New Dehli')
Marker.create(:name =>'New-York')
Done, they appear on the map!
NOTE: If for some reason some Marker doesn't have coordinates, the map will not be displayed, and you'll get a "too much recursion" Error in js console.
To avoid this, you can make sure all your Markers have coordinates by enabling after_validation :geocode
in your model, and launching this in in your console :
Marker.where(latitude: nil).or(Marker.where(longitude: nil)).each{|marker| marker.save}
Saving the marker triggers the validation, which triggers the geocoding.
If for some reason you still have non-geocoded Markers, change your js to :
functioninitMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4
});
var bounds = new google.maps.LatLngBounds();
var n = markers.length;
for (var i = 0; i < n; i++) {
var lat = markers[i].latitude;
var lng = markers[i].longitude;
if (lat == null || lng ==null){
console.log(markers[i].name + " doesn't have coordinates");
}else {
var marker = new google.maps.Marker({
position: {lat: parseFloat(lat), lng: parseFloat(lng)},
title: markers[i].name,
map: map
});
bounds.extend(marker.position);
}
}
map.fitBounds(bounds);
}
Post a Comment for "Google Maps - Setting It Up To Work With Rails 5 - Geocoder Not Geocoding"