Putting PHP variables into javascript

I’ve created a simple theme options page for my site. The options page contains three input fields. I can output the the fields by using get_option.

The three fields are called using the following:

Read More
<?php echo get_option( 'map_zoom' ); ?>
<?php echo get_option( 'map_longitude' ); ?>
<?php echo get_option( 'map_latitude' ); ?>

These variables are for controlling the zoom level, the longitude and latitude of a map. I have a javascript file that renders the map using the google maps api. I’d like to put these variables into that javascript file. When I put the javascript into a php file and add these variables the map renders but I lose all the rest of my map functions which are considerable. Also I then have to call the script php in the header instead of using wp_enqueue_script in the functions file.

Here is the map javascript:

var infowindow = new google.maps.InfoWindow();
var shadow = new google.maps.MarkerImage('/wp-content/themes/re-aligned/images/shadow.png', new google.maps.Size(37, 34) );


var markers = [];
var categories = [
    {
        name: 'People',
        slug: 'people',
        url: 'marker-people.png'
    }, {
        name: 'Works',
        slug: 'works',
        url: 'marker-works.png'
    }, {
        name: 'Discourse',
        slug: 'discourse',
        url: 'marker-discourse.png'
    }, {
        name: 'Other',
        slug: 'other',
        url: 'marker.png'
    }
];

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

function initialize() {

    jQuery('body').append(jQuery('<div id="toolbar"><h2>Map Categories</h2></div>'));

    // add checkboxes to toolbar
    for (var i = 0; i < categories.length; i++) {
        jQuery('#toolbar').append(
            jQuery('<input />', {
                type: 'checkbox',
                id: 'tog-marker-'+categories[i].slug,
                name: 'tog-marker-'+categories[i].slug,
                class: 'squaredTwo',
                value: i,
                checked: true
            })
        );
        jQuery('#toolbar').append(
            categories[i].name
        );
    }

    jQuery('#toolbar > input[type=checkbox]').click(function() {
        for(var i = 0; i < markers.length; i++) {

            if(markers[i].icon.url.endsWith(categories[jQuery(this).val()].url)) {
                if(jQuery(this).is(':checked')) markers[i].setVisible(true);
                else markers[i].setVisible(false);

            }
        }
    });

    // Create an array of styles.
    var styles = [

        {
            "featureType": "landscape.natural",
            "stylers": [
                { "color": "#ff412d" },
                { "visibility": "on" }
            ]
        },{
            "featureType": "administrative.land_parcel",
            "stylers": [
                { "visibility": "off" }
            ]
        },{
            "featureType": "administrative.neighborhood",
            "stylers": [
                { "visibility": "off" }
            ]
        },{
            "featureType": "administrative.province",
            "stylers": [
                { "visibility": "simplified" }
            ]
        },{
            "featureType": "administrative.country",
            "stylers": [
                { "visibility": "on" }
            ]
        },{
            "featureType": "water",
            "stylers": [
                { "color": "#ffebc5" }
            ]
        },{
            "featureType": "road",
            "stylers": [
                { "visibility": "simplified" },
                { "color": "#ffebc5" }
            ]
        },{
            "featureType": "poi",
            "stylers": [
                { "visibility": "off" }
            ]
        },{
            "featureType": "road.highway",
            "stylers": [
                { "visibility": "off" }
            ]
        },{
            "featureType": "administrative.locality",
            "stylers": [
                { "visibility": "off" }
            ]
        },{
            "featureType": "administrative.country",
            "elementType": "geometry",
            "stylers": [
                { "visibility": "off" }
            ]
        }
    ];

    // Create a new StyledMapType object, passing it the array of styles,
    // as well as the name to be displayed on the map type control.
    var styledMap = new google.maps.StyledMapType(styles,
        {name: "Styled Map"});

    // Create a map object, and include the MapTypeId to add
    // to the map type control.
    var mapOptions = {
        zoom: <?php echo get_option( 'map_zoom' ); ?>,
        scrollwheel: true,
        center: new google.maps.LatLng(<?php echo get_option( 'map_latitude' ); ?>, <?php echo get_option( 'map_longitude' ); ?>),
        mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style'],
        mapTypeControl: true,
        mapTypeControlOptions:  {
            style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
            position: google.maps.ControlPosition.BOTTOM_CENTER
        },
        panControl: false,
        panControlOptions: {
            position: google.maps.ControlPosition.TOP_RIGHT
        },
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.LARGE,
            position: google.maps.ControlPosition.LEFT_CENTER
        },
        scaleControl: false,
        scaleControlOptions: {
            position: google.maps.ControlPosition.LEFT_CENTER
        },
        streetViewControl: false,
        streetViewControlOptions: {
            position: google.maps.ControlPosition.LEFT_TOP
        }
    };
    var map = new google.maps.Map(document.getElementById('map'), mapOptions);

    var oms = new OverlappingMarkerSpiderfier(map);

    //Associate the styled map with the MapTypeId and set it to display.
    map.mapTypes.set('map_style', styledMap);
    map.setMapTypeId('map_style');

    oms.addListener('click', function(marker, event) {
        infowindow.setContent(marker.desc);
        infowindow.open(map, marker);
    });


    for (var i = 0; i < locations.length; i++) {
        var marker = new google.maps.Marker({
            position: locations[i].latlng,
            desc: locations[i].info,
            icon: locations[i].marker,
            shadow: shadow,
            map: map
        });
        oms.addMarker(marker);
        markers.push(marker);
    }

}

How can i correctly output the variables into the javascript file?

UPDATE:

After taking on board the information about wp_localize_script I’ve done the following:

I’ve put this in my functions.php

wp_enqueue_script( 'map-script' );
    $object = array(
        'zoom' => get_option('map_zoom'),
        'longitude' => get_option('map_longitude'),
        'latitude' => get_option('map_latitude'),
    );  
wp_localize_script('map-script', 'JSObject', $object);
    } 

and used JSObject.variable in my map javascript like so:

var mapOptions = {
        zoom: JSObject.zoom,
        scrollwheel: true,
        center: new google.maps.LatLng(JSObject.latitude, JSObject.longitude),
        mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style'],
        mapTypeControl: true,
        mapTypeControlOptions:  {
            style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
            position: google.maps.ControlPosition.BOTTOM_CENTER
        }

But that returns the error: Uncaught Error: Invalid value for property <zoom>: 9

9 is the actual zoom variable so it appears to be working sort of…

Related posts

2 comments

  1. Use wp_localize_script:

    wp_enqueue_script('YOUR_SCRIPT_HANDLE');
    $object = array(
        'zoom' => get_option('map_zoom'),
        'longitude' => get_option('map_longitude'),
        'latitude' => get_option('map_latitude'),
    );
    wp_localize_script('YOUR_SCRIPT_HANDLE', 'JSObject', $object);
    

    And then use it in your JS file like JSObject.zoom and the like.

Comments are closed.