简体   繁体   中英

how to pass php variables to javascript map function

Just want to pass php variables $x and $y to javascript map function (as lat and long). Please help. Here is my controller:

<?php
$x = 25.114667;
$y = 55.137797;
?>

Here is my JS file:

function initialize()
    {
    var myCenter = new google.maps.LatLng(lat,long);
    var mapOptions = {
      center:myCenter,
      zoom:12,
      mapTypeId:google.maps.MapTypeId.ROADMAP
      };
    var map=new google.maps.Map(document.getElementById("googleMap")
      ,mapOptions);

    }   google.maps.event.addDomListener(document.getElementById('showhidemap'), 'click', initialize);

you are passing string in you js variable lat and long . assign value directly as float
try this

 var lat = <?php echo $x; ?>;
 var long = <?php echo $y; ?>;

also must include the script with google map key on above of google map initialization.

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=GOOGLE_MAP_KEY&sensor=true"> </script>

GOOGLE MAP KEY : must be generate for your site.

see some urls might help you

https://developers.google.com/maps/tutorials/fundamentals/adding-a-google-map
https://developers.google.com/maps/signup?csw=1
https://developers.google.com/maps/documentation/javascript/tutorial

did you try to add

$x = 25.114667;
$y = 55.137797;

to some tag like

<div data-lat="<?php echo $y; ?>" data-long="<?php echo $y; ?>" id="showhidemap">show map</div>

You need to create a Javascript object in your .php file, just before your include your javascript file (the one containing the above fragment), which will be filled by your longitude/latitude information. Like this:

YOUR PHP FILE

<html>
   ...
   <script type="text/javascript">
      var mapLangLat = {
         long:<?php echo $x; ?>,
         lati:<?php echo $y; ?>
      };
   </script>
   <script src="my_remote_script.js"></script>
   ...

YOUR JAVASCRIPT FILE

<script>
function initialize()
    {

    var lat = window.mapLangLat.lati;
    var long = window.mapLangLat.long;

    ...

It's required to find the PHP part above to be able to code that little javascript object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM