Search code examples
javascripthtmliframegeolocation

dynamic variables in an iframe


I am trying to use HTML5 geocoding to pass dynamic lat and long into an iframe. This is as far as I can get. I can't quite get the lat and lon to work into the iframe src.

How do I pass the variables into the iframe properly?

<!DOCTYPE html>
<html>
<body>

<script type="text/javascript">

function myLat(position) {
    text(position.coords.latitude);
}

function myLon(position) {
    text(position.coords.longitude);
}

document.write('<iframe id="forecast_embed" type="text/html" frameborder="0" height="245" width="100%" src="http://forecast.io/embed/#lat='+myLat+'&lon='+myLon+'&name=Your Location"> </iframe>');

</script>

</body>
</html>

Solution

  • Have you looked at the documentation for geolocation? Something like the following will do what you want:

    navigator.geolocation.getCurrentPosition(function(position) {
    
        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
    
        document.write('<iframe id="forecast_embed" type="text/html" frameborder="0" height="245" width="100%"' +
            'src="http://forecast.io/embed/#lat=' + lat + '&lon=' + lon + '&name=Your Location"> </iframe>');
    });