WordPress.org

Forums

PHP variable in Javascript (2 posts)

  1. Scott Chandler
    Member
    Posted 3 years ago #

    Hello

    I'm very new to PHP. On a WordPress site, I want to use custom Google Maps with the Javascript API V3. Some posts will have maps in them, and I want to use PHP variables to determine the unique locations, zoom level, info window text, etc. The Google Maps javascript will be in the footer with all the styles, map type and anything that will be consistent from map to map.

    So for posts which have a map, written in the post there will be something like:

    <?php
    $location = "-34.397, 150.644";
    $zoom = "8";
    ?>
    
    <div id="map"></div>

    And in the javascript in the footer theme file will be something like:

    <script type="text/javascript">
      function initialize() {
        var latlng = new google.maps.LatLng(<?=$location;?>);
        var myOptions = {
          zoom: <?=$zoom;?>,
              center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map"),
            myOptions);
          }
    </script>

    Plus all the other crap that Google requires. I have the exec-php plugin installed to allow PHP in posts.

    This works fine if I put it in any other php file, but not within WordPress. What am I doing wrong?

  2. vtxyzzy
    Member
    Posted 3 years ago #

    Javascript is not my strong suite, but give this a try. First, declare $location and $zoom as globals in both sets of code:

    <?php
    global $location,$zoom;
    $location = "-34.397, 150.644";
    $zoom = "8";
    ?>
    
    <div id="map"></div>

    Then, echo the variables in your footer:

    <?php global $location, $zoom; ?>
    <script type="text/javascript">
      function initialize() {
        var latlng = new google.maps.LatLng(<?php echo $location;?>);
        var myOptions = {
          zoom: <?php echo $zoom;?>,
              center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map"),
            myOptions);
          }
    </script>

Topic Closed

This topic has been closed to new replies.

About this Topic