I'm using the following javascript
to pick a point on the map and populate the address field with this point. The address field is used inside a rails from tag in order to search by the address:
<%= form_tag search_path, method: "get", id: "other-form" do %>
<%= text_field_tag :location, params[:location], id:"address" %>
<%= submit_tag "submit", :id=> "my-button" %>
<%= text_field_tag :search_other, params[:search] %>
<%= hidden_field_tag :lat %>
<%= hidden_field_tag :lng %>
<% en d%>
<div id="map_canvas"></div>
<script>
var map;
var geocoder;
var mapOptions = { center: new google.maps.LatLng(0.0, 0.0), zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP };
function initialize() {
var myOptions = {
center: new google.maps.LatLng(38.89103282648849, -97.646484375),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
var marker;
function placeMarker(location) {
if(marker) { //on vérifie si le marqueur existe
marker.setPosition(location); //on change sa position
} else {
marker = new google.maps.Marker({ //on créé le marqueur
position: location,
map: map
});
var circle = new google.maps.Circle({
map: map,
radius: 24140, // 15 miles in metres
fillColor: '#08aa23'
});
circle.bindTo('center', marker, 'position');
}
document.getElementById('lat').value=location.lat();
document.getElementById('lng').value=location.lng();
getAddress(location);
var cookie_val = ('other_lat_lng', location.lat() + "," + location.lng())
document.cookie = "other_lat_lng=" + escape(cookie_val);
}
var a_message = "<%= I18n.t 'map_other' %>"
function getAddress(latLng) {
geocoder.geocode( {'latLng': latLng},
function(results, status) {
if(status = google.maps.GeocoderStatus.OK) {
if(results[0]) {
document.getElementById("address").value = results[0].formatted_address;
} else {
document.getElementById("address").value = a_message;
}
} else {
document.getElementById("address").value = status;
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
Then on the results page I have a link_to
which redirects to another page with the map and the search form. When redirecting, I would like this new page to keep the same point that was choosen in the previous search.
You can expose the :lat and :lng by passing them through the link_to, then exposing them to the JS side with some data tags.
<%= link_to "new link", new_page_path(lat: params[:lat], lng:
params[:lng]) %>
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.