简体   繁体   中英

Ruby on Rails - Geocoder view

Im trying to use geocoder for displaying a location based on an address.

My question is, what do I put in the view to show an interactive map once I got the Lat and Long from the address the user inserted in the database?

my address model

 belongs_to <another model>
 attr_accessible <all addresses attributes including latitude and longitude>

 geocoded_by :address

 after_validation :geocode, :if => :address_changed?

The fields Latitude and Longitude are automatically calculated after I insert the address.

I've followed Ryan's Rail Cast tutorial but at the end, instead of displaying a static image I want to display a map, google maps interactive style. How can I achieve this?

If've taken a look at Google-Maps-for-Rails but couldn't understand how very well like how to get a single map on location in the show view.

Take a closer look at Google-Maps-for-Rails . That gem makes it trivial, and the instructions on how to get the interactive map in your view are quite clear:

(I'll presume your Address model belongs_to a User model. Change names as appropriate.)

If you just want the one specific user on the map, of course you could change the controller:

@json = User.find(params[:id]).address.to_gmaps4rails

In your view:

<%= gmaps4rails(@json) %>

There are many helpful examples for the Google Maps API available here . In the simplest case, you can do something like this:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
  var lat = <%= @model.latitude %>, 
      lon = <%= @model.longitude %>,
      map;
  function initialize() {
    var myOptions = {
      center: new google.maps.LatLng(lat, lon)
    };
    map = new google.maps.Map(document.getElementById('map_canvas'),
        myOptions);
  }

  google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map_canvas"></div>

Just replace @model.latitude and @model.longitude with the corresponding geocoded fields in your model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM