I need to pass coordinates to javascript from HTML 5 using the data- tag for use in Google Maps. I am not very good at Javascript and I cannot find a solution anywhere. This is the html with ruby(erb), the coordinates are correctly available in HTML if the page source is viewed:
<div id="google_map_section" data-latitude="<%= @place.latitude %>" data-longtitude ="<%= @place.longtitude %>"></div>
And the javascript:
$(function initialize() {
var latlng = new google.maps.LatLng(
parseFloat($("#google_map_section").attr("data-latitude")),
parseFloat($("#google_map_section").attr("data-longtitude"))
);
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("google_map_section"),
myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map
});
});
Question 1: The values are not being passed to javascript. Why not? Should I use:
$("#google_map_section").data("latitude")?
$("#google_map_section").attr("data-latitude")?
$("#google_map_section").getAttribute("data-latitude")?
I tried them all with no luck. Sometimes the map seems to render but no images are shown.
Question 2: Do I have to use onload=”initialize()” on the body tag or can it be used on any tag?
Using attr should work fine:
Working example
You do not need to use the onload inline event handler however your initialise method should be an anonymous method instead of a named method.
Replace:
with: