I am using this script on display google maps on my wordpress site:
<head>
<script>
function initialize()
{
var mapProp = {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap",mapProp);
}
</script>
</head>
I have set up two custom fields “fl_long” , “fl”lat” for the longitute and latitude. How do I modify the code above so that the values are taken from the custom fields instead of being hardcoded numbers?
google.maps.event.addDomListener(window, 'load', initialize);
Here’s a version that uses
wp_localize_script()
, as suggested by others. It’s just a little bit cleaner, since you don’t mix your PHP with your JS, and generally a neat way to pass things from the server side to your JavaScript.First, put the following code either in your plugin or your functions.php (I use a plugin so I named it accordingly, but you can name it whatever you want):
Note that the call to your
wp_localize_script()
must occur between the call towp_register_script()
(for the file in which you’ll be using those lat-long coordinates generated with PHP), and the call towp_enqueue_script()
. This should output something like this in your page source:Then inside your JS file you can have your function use the
my-coordinates
object:Feel free to ask questions if something is not clear from the code.
Try to add the script to the head with a wordpress hook: