Keyvman
Keyvman

Reputation: 59

Showing current location with Google Places

I used this sample code below to show an autocomplete search for Google Places. It currently defaults the current location to Sydney, Australia.

https://developers.google.com/maps/documentation/javascript/examples/places-searchbox

I am currently gathering user location as latitude and longitude:

schema.rb

  create_table "users", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.float    "latitude"
    t.float    "longitude"
  end

How do I modify what I assume is this part (not sure why there are two sets of coordinates there)

 var defaultBounds = new google.maps.LatLngBounds(
     new google.maps.LatLng(-33.8902, 151.1759),
     new google.maps.LatLng(-33.8474, 151.2631));
 map.fitBounds(defaultBounds);

to default to my user's current location?

Upvotes: 0

Views: 1306

Answers (1)

David Battersby
David Battersby

Reputation: 266

I have built a similar solution to this in Rails. Basically I make an ajax request to a method in my rails controller and return the user record as JSON which can be used to setup our map. I have adapted the code to fit your exact needs.

Let's start by setting up a separate js file under the asset pipeline:

Place the following under /app/assets/javascripts/gmap.js

  var worldMap = {
    init: function(){
      // fetch our user record for lat/long
      $.ajax({
        url: '/user/location',
        dataType: 'json',
        success: function( data ){
          worldMap.lat = data.latitude;
          worldMap.lng = data.longitude;
          worldMap.setupMap();
        }
      });
    },
    setupMap: function(){
      // we now have user location loaded so build map
      worldMap.map = new google.maps.Map( document.getElementById( "map" ), {
        zoom: 3,
        center: {
          lat: worldMap.lat,
          lng: worldMap.lng
        }
      });

      // now lets add autocomplete search
      var searchbox = (document.getElementById('search-controls'));
      var input = document.getElementById('pac-input');
      worldMap.map.controls[ google.maps.ControlPosition.LEFT_TOP ].push( searchbox );

      var autocomplete = new google.maps.places.Autocomplete(input);
      autocomplete.bindTo('bounds', worldMap.map);

      google.maps.event.addListener(autocomplete, 'place_changed', function() {
        var place = autocomplete.getPlace();
        if (!place.geometry) { return; }

        // center map on chosen location
        if (place.geometry.viewport) {
          worldMap.map.fitBounds(place.geometry.viewport);
        } else {
          worldMap.map.setCenter(place.geometry.location);
          worldMap.map.setZoom(17);
        }
      });
    }
  }

Then we can call our new map setup code once the DOM has loaded, add into /app/assets/javascripts/application.js:

window.onload = function(){
  worldMap.init();
}

Now we can setup our routes, add this line to /config/routes.rb:

get 'user/location', :controller => 'users', :action => 'user_location', :as => 'user_latlng'

Then finally add the method to our users controller /app/controllers/users_controller.rb:

def user_location
  @user = User.select(:latitude, :longitude).where(id: current_user.id).limit(1)
  render json: @user.first
end

In your view you will want to have your search box and the map div that our JS is looking for:

<div id="search-controls" class="controls">
  <input type="text" id="pac-input" placeholder="Search" />
</div>

<div id="map"></div>

Upvotes: 1

Related Questions