In my Rails app I have a helper method location
that gets the coordinates for a given IP address and makes them available across all controllers and views. For example location.latitude
returns the latitude of the user. You get the idea.
I also have some Javascript that draws a Map from the Google Maps API based upon a given lat/lon pair. The problem is that I have no idea how to pass the location
params into the JavaScript!
The JavaScript resides in 'application.js' and looks like this:
$(document).ready(function()
{
//Map options...I want the params to go into the var 'MapOptions' below
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(40.764698,-73.978972),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Setup and Draw the Map...
//....................................
};
The map itself gets called in the HTML like so. There isn't an obvious way to pass params.
<div id="map_canvas">
<!-- The Map gets drawn here! -->
</div>
I know this is probably an obvious question, but I've never had to pass a parameter from my application to Javascript this way before.
I think data attributes work well here.
html
<div id="map_canvas" data-latitude="40.764698" data-longitude="-73.978972">
<!-- The Map gets drawn here! -->
</div>
or with your helpers
<div id="map_canvas" data-latitude="<%= location.latitude %>" data-longitude="<%= location.longitude %>">
<!-- The Map gets drawn here! -->
</div>
js
$(document).ready(function() {
//Map options...I want the params to go into the var 'MapOptions' below
function initialize() {
var mapDiv = $('#map_canvas');
var lat = mapDiv.data('latitude'),
lng = mapDiv.data('longitude');
var mapOptions = {
center: new google.maps.LatLng(lat,lng),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Setup and Draw the Map...
//....................................
};
You can assign lat and long to the hidden fields in the view. And in your applicatons.js script just get them like $("#lat").val()
Not the ultimate solution, but should work well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With