www.webdeveloper.com
Page 2 of 2 FirstFirst 12
Results 16 to 25 of 25

Thread: Assigning a js variable to a php variable

  1. #16
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,266
    Sorry for this doublon.

  2. #17
    Join Date
    Nov 2010
    Posts
    1,085
    that's because in my version the html is passed from the loop. this is the full function:

    Code:
    function createMarker(latlng, label, html,map) {
    		var marker = new google.maps.Marker({
            position: latlng,
    		title:label,
            map: map,
            zIndex: Math.round(latlng.lat()*-100000)<<5
            });
    
    		google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent(html); 
            infowindow.open(map,marker);
            });
        }
    but if you really wanted to do the ajax call at the time of the click (and I understand the rest of it), it would have to be something like this:

    Code:
    function createMarker(latlng, label,map) {
    	var marker = new google.maps.Marker({
            position: latlng,
    	title:label,
            map: map,
            zIndex: Math.round(latlng.lat()*-100000)<<5
            });
    
    google.maps.event.addListener(marker,'click',function(){
        alert(marker.title.substr(0,4))
    	infowindow.setContent(sndRqt('ajx_mtr.php?arp='+marker.title.substr(0,4),function(r){ return r.responseText)});
    		infoWindow.open(map,marker);
              });
        }
    and that function called from inside the loop.

    but I don't know if you can return responseText like that.

  3. #18
    Join Date
    Nov 2010
    Posts
    1,085
    hmm. Well, kind of. But the next problem was that the window wanted to open before the text had come back from the ajax request. So the content setting has to go into the callback function. This seems to work, anyway, although I still think it makes more sense just to get all the data on page load...

    html/js:
    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
    <style>
    html, body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    
    #map_canvas {
      height: 100%;
    }
    
    @media print {
      html, body {
        height: auto;
      }
    
      #map_canvas {
        height: 650px;
      }
    }
    </style>
    </head>
    <body>
    
    
    <div id="map_canvas"></div>
    <script type = "text/javascript">
    var infowindow = new google.maps.InfoWindow();
    
    var xmlObj=false;
    	var xmlFct=[function(){return new XMLHttpRequest()}
    		,function(){return new ActiveXObject("Msxml2.XMLHTTP")}
    		,function(){return new ActiveXObject("Msxml3.XMLHTTP")}
    		,function (){return new ActiveXObject("Microsoft.XMLHTTP")}];
    	for (var i=0;i<xmlFct.length;i++) {try{xmlObj = xmlFct[i]();}catch(e){continue;}break;}
    	
    	sndRqt=function(url,cllbck,pstDta){
    		var req=xmlObj;
    		if (!req) return;
    		var mth=(pstDta)? "POST":"GET";
    		req.open(mth,url,true);
    		//req.setRequestHeader('User-Agent','XMLHTTP/1.0');
    		if (pstDta) req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    		req.onreadystatechange=function(){
    			if (req.readyState!=4) return;
    			if (req.status!=200 && req.status!=304) return;
    			cllbck(req);}
    		if (req.readyState==4) return;
    		req.send(pstDta);
    	};
      
    function makeMap(){ 
    
    	
    
      var mapOptions = {
              zoom: 7,
              center: new google.maps.LatLng(46.76305556,2.424722222),
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };
    
            var map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
          
    	  var stations = [[]];
    stations[1]=['LFAQ','ALBERT','',' ',49.9725,2.69138888888889];
    stations[2]=['LFAT','LE TOUQUET','123.125','03 21 06 62 84',50.5147222222222,1.6275];
    stations[3]=['LFBA','AGEN','129.6',' ',44.1747222222222,0.590555555555556];
    stations[4]=['LFBC','CAZAUX','',' ',44.535,-1.13138888888889];
    stations[5]=['LFBD','BORDEAUX MERIGNAC','131.150','05 57 92 81 04',44.8286111111111,-0.715277777777778];
    stations[6]=['LFBE','BERGERAC','127.475','05 53 63 53 55',44.8244444444444,0.520555555555556];
    stations[7]=['LFBG','COGNAC','244.450',' ',45.6583333333333,-0.3175];
    stations[8]=['LFBH','LA ROCHELLE','126.875','05 46 00 13 92',46.1791666666667,-1.19527777777778];
    stations[9]=['LFBI','POITIERS','121.775',' ',46.5875,0.306666666666667];
    stations[10]=['LFBL','LIMOGES','128.075','05 55 48 40 37',45.8608333333333,1.18027777777778];
    
            for (var i = 0; i < stations.length; i++) {
    		var station = stations [i];
    		var myLatLng = new google.maps.LatLng(station[4], station[5]);
    		var titre=station[0]+"/"+station[1]+"\n"+station[2]+"/"+station[3]
    		
            var marker = createMarker(myLatLng,titre,map);
    		  }
      }
    
    		function createMarker(latlng, name,map) {
    		var marker = new google.maps.Marker({
            position: latlng,
    		title:name,
            map: map,
            zIndex: Math.round(latlng.lat()*-100000)<<5
            });
    		
    		google.maps.event.addListener(marker, 'click', function() {
    		sndRqt('ajx_mtr.php?arp='+name.substr(0,4),function(r){
    		infowindow.setContent(r.responseText);
            infowindow.open(map,marker);
    			});
            });
        }
    makeMap();
    </script>
    </body>
    </html>
    php:
    PHP Code:
    <?php
      header
    ("Content-Type: text/html; charset=utf-8");
      if (!empty(
    $_GET["arp"])){$arp=$_GET["arp"];
     
    $xml simplexml_load_file("http://aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&stationString=".$arp."&hoursBeforeNow=1");

    $metar=$xml->data->METAR[0];
    $name=$metar->station_id;
    $temp=$metar->temp_c;
    $dir=$metar->wind_dir_degrees;
    $sp=$metar->wind_speed_kt;
    $vis=$metar->visibility_statute_mi;
    $str=$name "<br>temperature: " $temp "<br> wind direction: " $dir "<br>" "wind speed: " $sp "<br>" "visibility: " $vis;
    echo 
    $str;
      exit(
    $xml);}
      exit(
    "No response !");
    ?>

  4. #19
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,266
    I do not understand, I never see an infoWindow ! Have you tested your last proposal which «seems» to work ?

    Otherwise, it seems more rational not to do all the work of interpretation all stations while the user does not click on all stations and wants to have the latest information.

    I had made ​​a localisation page (with v2) which seem to work when Google wants it (only on my computer ?).
    Last edited by 007Julien; 12-31-2012 at 07:01 AM.

  5. #20
    Join Date
    Nov 2010
    Posts
    1,085
    you can see my code live here

    your other page is using v2 of the API, which is now deprecated - it is better to change to v3

  6. #21
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,266
    Thanks ! I will try to see an InfoWindow and remove my old page...

    EDIT : Ok ! The InfoWindow must be a global variable...
    Last edited by 007Julien; 12-31-2012 at 09:15 AM.

  7. #22
    Join Date
    Nov 2010
    Posts
    1,085
    Quote Originally Posted by xelawho View Post
    one globally accessible infowindow and places a listener on each marker so that the one window will move and change contents on the click...
    yes...

  8. #23
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,266
    Here is a new localisation page...
    It misses only the round corners (for InfoWindow) and the weather on the nearest airport with this database !

    Happy Holidays and New Year.
    Last edited by 007Julien; 12-31-2012 at 10:40 AM.

  9. #24
    Join Date
    Nov 2010
    Posts
    1,085
    cool. here's how I'd do the other one, with the ability to add the weather stations IDs to station_str and not have to hardcode all those coordinates:

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
    <style>
    html, body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    
    #map_canvas {
      height: 100%;
    }
    
    @media print {
      html, body {
        height: auto;
      }
    
      #map_canvas {
        height: 650px;
      }
    }
    </style>
    </head>
    <body>
    
    
    <div id="map_canvas"></div>
    <script type = "text/javascript">
    var infowindow = new google.maps.InfoWindow();
    
    function downloadUrl(callback) {
    url="ajx_mtr2.php"
    var xmlFile = window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject('Microsoft.XMLHTTP');
    	xmlFile.onreadystatechange = function() {
       if (xmlFile.readyState == 4) {
         callback(xmlFile, xmlFile.status);
       }
     };
    xmlFile.open("GET", url, true); 
    xmlFile.send(null);
    }
      
     
    function init(){
     var mapOptions = {
              zoom: 7,
              center: new google.maps.LatLng(46.76305556,2.424722222),
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };
    
         var map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
    
    	 downloadUrl(function(obj) { 
    var r = JSON.parse(obj.responseText);
    
    var stats=r.data.METAR;
    
    
    	var station_str="LFAQ,LFAT,LFBA,LFBC,LFBD,LFBE,LFBG,LFBH,LFBI,LFBL";
    
            for (var i = 0; i < stats.length; i++) {
    		var station = stats[i];
    		if(station_str.indexOf(station.station_id)!=-1){
    		var myLatLng = new google.maps.LatLng(station.latitude, station.longitude);
    		var name=station.station_id
    		var temp=station.temp_c;
    		var dir=station.wind_dir_degrees;
    		var sp=station.wind_speed_kt;
    		var vis=station.visibility_statute_mi;
    		var str=name+"<br>temperature: "+temp+"<br>"+"wind direction: "+dir+"<br>"+"wind speed: "+sp+"<br>"+"visibility: "+vis;
    		var marker = createMarker(myLatLng,name,str,map);
    				}
    		  }
      });
    }
    		function createMarker(latlng, name,str,map) {
    		var marker = new google.maps.Marker({
            position: latlng,
    		title:name,
            map: map,
            zIndex: Math.round(latlng.lat()*-100000)<<5
            });
    		
    		google.maps.event.addListener(marker, 'click', function() {
    		infowindow.setContent(str);
            infowindow.open(map,marker);
            });
        }
    init();	
    </script>
    </body>
    </html>
    with php
    PHP Code:
    <?php
      header
    ("Content-Type: text/html; charset=utf-8");
    $xml simplexml_load_file("http://aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&stationString=LFPG%20LF*&hoursBeforeNow=1");
    echo 
    json_encode($xml);
      exit(
    $xml);
      exit(
    "No response !");
    ?>

  10. #25
    Join Date
    Dec 2012
    Posts
    8
    Hi Everybody,
    Thanks for your answers to my problem « assigning a js variable to a php variable » some days ago. Here’s an update of what I finally succeeded doing. In fact I made it work . Here’s how :

    1) PHP :Reading a textfile (fgets) with meterological station details (code, name, latitude, longitude etc) in PHP variables indexed with (let’s say) $n. For instance : $code_station[$n] gets the station code.

    2) PHP : Get the meteorological information from : http://aviationweather.gov/adds/metars (file_get_contents($url)) for all these stations.

    3) PHP : Per station, prepare data to complete preceding PHP information.

    Here I have to switch to JavaScript to display the Google Map and one marker per station. To do so, I have to recuperate the above PHP information into JS information. This was my issue when I asked for help. Here’s how it works :

    4) Consider the following PHP code which does the trick :

    // TRANSFERT DES DONNEES LUES DANS VARIABLE JAVASCRIPT
    echo "<script>var nbre_stations=".$nbre_stations."</script>";
    echo '<script>var stations = [[]]</script>';
    for ($i=0;$i<$nbre_stations;$i++) // ici on va remplir une variable JS avec les données lues en PHP
    {
    echo "<script>stations[".$i."]=['".$code_station[$i]."','".$nom_station[$i]."','".$atis_station[$i]."','"
    .$notel_station[$i]."',".$lat_station[$i].",".$lon_station[$i].",'"
    .$calc_metar[$i]."','".$calc_taf[$i]."','".$srss[$i]."']</script>";
    }

    5) From this point on everything is Javascript, and the map is displayed with the adequate information.

    You can see the result here http://www.volets10.fr/V10metartaf_carte.php . I preferred « mouseover » to « click ».
    (PS. If you are interested, some parameters may be applied : ?reg=x, where x is a combination of 1,2,3,4,5 corresponding to the french telephone regions. For example : ?reg=125 will display stations from Paris region, north-west and south-west. You can add &max=y where y is the max. number of stations per region to display. You can also ask for stations individually by their OACI codes. Example : ?oaci=lfpg,lfpt,lfrh will display Charles de Gaulle, Pontoise and Lorient) .

    Cheers and thanks for your help.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles