Reputation: 13939
I have setup gmaps-autocomplete-rails gem in my application, and I have an UI callback that can let me set the GPS coordinates to an input
function autocompleteMap(){
var completer;
completer = new GmapsCompleter({
...
updateUI: function(address, latLng) {
$("#myObject_coordinates").val(
"["+latLng.lat()+", "+latLng.lng()+"]"
)
}
});
}
My mongoid model accept coordinates as an array to be used with the geocoder gem. Is there a practical way to pass the lat/lng as an array via input fields ? Some SO answers suggested to use
f.text_field(:coordinates, multiple: true)
but I cannot figure out how I should fill the value so it is interpreted as an array in the controller (and preserve lat/Lng order)
Get an array from a rails form doesn't help in my case, since I am using javascript to fill a single input (or should I set it up to fill two inputs ?)
Right now with the above js function, the associated rails params becomes
params[:my_object][:coordinates] # => ["[x, y]"]
# Wanted: [x, y]
Do I have to parse the string manually as an array, or is there a trick ?
Also, this input needs to be sanitized and the numbers ocnverted to floats, any guideline, protip on how to do that "neatly" ?
Upvotes: 1
Views: 185
Reputation: 11813
You need to add 2 fields and you probably want to make them hidden.
f.hidden_field(:coordinates, multiple: true, class: 'lat', id: 'lat')
f.hidden_field(:coordinates, multiple: true, class: 'lng', id: 'lng')
// ...
updateUI: function(address, latLng) {
$('input.lat').val(latLng.lat());
$('input.lng').val(latLng.lng());
}
// ...
# Will receive it as an array
params[:my_object][:coordinates] # => [x, y]
Upvotes: 0