Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Geocoder restrict region/country

I would like to restrict my search for latitude/long. for a specific region (i.e. New Zealand).

Google provides some parameters that can be set to achieve the results, such as : 'componentsRestriction' and 'region'. I tried to set the same thing in config/initializers/geocoder.rb but it did not work. Here is my code.

Geocoder.configure(

    :lookup => :google,
    :timeout => 5,
    :units => :km,


    # version 1
    :google => {
        :components => {:country => 'NZ'},
        :region => 'NZ',
    },
    # version 2
    :components => {:country => 'NZ'},
    :region => 'NZ',

)

Here is a documentation from google, where they permit specification of extra parameters, such as region for the lookup. https://developers.google.com/maps/documentation/geocoding/

like image 640
Ar Thur Avatar asked Nov 11 '14 07:11

Ar Thur


1 Answers

Bit late on this but I am looking at the same issue. Having looked at the initializer options in the config (see below) I believe that you cannot set the region in the initializer. Probably because some API's support it and some do not.

https://github.com/alexreisner/geocoder/blob/master/lib/geocoder/configuration.rb

I am using geocoder with Google maps and found a couple of ways of doing it. In my example I am looking for Kenilworth. It is a place in the United Kingdom but when querying without a region I get Kenilworth in New Jersey. I believe this is returned because Google has a US regional bias, which I would expect. I am using geocoder's near to find venues in my venues model based on criteria entered by a user. I assume a 1 mile distance on my near parameter in the examples.

Method 1

Pass the region into the search or coordinates methods:

Geocoder.search("Kenilworth", :params => {:region => "gb"})
Geocoder.coordinates("Kenilworth", :params => {:region => "gb"} )

The search returns an array which will have the lat\long you need for the town. The coordinates will just return the latitude and longitude coordinates, for my needs this is the best option.

To get this working with the near method you can take the extracted coordinates and use them in the near:

Venue.near(Geocoder.coordinates("Kenilworth", :params => {:region => "gb"} ), 1 )

Method 2

Concatenate the country into the location parameter specified:

 Venue.near( params["location"] << ", United Kingdom" , 1)

Producing:

Venue.near("Kenilworth, United Kingdom", 1 )

I believe that both methods would only use 1 API call to google. I can't verify that at the moment though because I can't log into the google developers console to check out the API usage.

I have read that the region can be a bit hit and miss but I haven't had any issues with using it in tests.

Hopefully this will help others with the same issue.

like image 91
Mark Davies Avatar answered Oct 16 '22 05:10

Mark Davies