Search code examples
phpgeolocationgoogle-maps-api-3

Google Maps API - setting php variable as javascript variable


I am using the Google Maps API and the W3C Standard to get a user's geolocation. I have it set up as basics - using the code from [Google's documentation][1].

Now I'm integrating this into my website and need it imputed into my mysql database. I want to set a PHP variable as a JavaScript variable (basically setting a PHP variable as the latitude and longitude). But I'm having no success of doing this.

EDIT:

Basically I want to make $phpvar = $jsvar. Making a php variable = my javascript variable.

Here's the code:

var initialLocation;
var siberia = new google.maps.LatLng(60, 105);
var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var browserSupportFlag =  new Boolean();

function initialize() {
  var myOptions = {
    zoom: 6,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  // Try W3C Geolocation (Preferred)
  if(navigator.geolocation) {
    browserSupportFlag = true;
    navigator.geolocation.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
      map.setCenter(initialLocation);
    }, function() {
      handleNoGeolocation(browserSupportFlag);
    });
  // Try Google Gears Geolocation
  } else if (google.gears) {
    browserSupportFlag = true;
    var geo = google.gears.factory.create('beta.geolocation');
    geo.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
      map.setCenter(initialLocation);
    }, function() {
      handleNoGeoLocation(browserSupportFlag);
    });
  // Browser doesn't support Geolocation
  } else {
    browserSupportFlag = false;
    handleNoGeolocation(browserSupportFlag);
  }

  function handleNoGeolocation(errorFlag) {
    if (errorFlag == true) {
      alert("Geolocation service failed.");
      initialLocation = newyork;
    } else {
      alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
      initialLocation = siberia;
    }
    map.setCenter(initialLocation);

} }

Any help would be great! Please be specific with me because I'm new to this Google Map API.

Thanks! :)


Solution

  • You can store a PHP variable as a Javascript variable like this:

    <script type="text/javascript">
        var geoloc = '<?php echo $geoloc; ?>';
    </script>
    

    You can then use this variable as required. If you can give an example code, I would try to let you know more accurately.