Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strike>That is because you declare your variables within the function. The variables gets private to the <code>initialize</code> function and can only be accessed from within it. If you need to be able to access your variables outside of the initialize function, then move the variable declaration out of the function.</p> <pre><code>var lat; var lon; function initialize() { ... </code></pre> <p>Have a look at this <a href="https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals#Variable_scope" rel="nofollow">MDN article</a> about variable scope in JavaScript. </strike></p> <p><strong>UPDATE</strong></p> <p>Looking through the code again I realize that the problem isn't variable scope, got confused by the indentation. I'm not familiar with the Geolocation API but I believe that the problem might be that the <code>navigator.geolocation.getCurrentPosition()</code> is asynchronous, as it will have to wait for the user to allow the website to get the position of the device. Therefor <code>myOptions</code> will have been assigned before the actual position have been retrieved - thus <code>lat</code> &amp; <code>lng</code> are still undefined when <code>myOptions</code> is assigned.</p> <p>Try this instead:</p> <pre><code>//main function here function initialize() { var lat, lon, map, myOptions; //check if user has geo feature if(navigator.geolocation){ navigator.geolocation.getCurrentPosition( //get position function(position){ lat = position.coords.latitude; lon = position.coords.longitude; //init map myOptions = { center: new google.maps.LatLng(lat, lon), zoom: 16, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); }, // if there was an error function(error){ alert('ouch'); }); } //case the users browser doesn't support geolocations else { alert("Your browser doesn't support geolocations, please consider downloading Google Chrome"); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload