Nysa
Nysa

Reputation: 445

Calling a function somewhere else inside a script tag doesn't work

For some reason, the code in the same script tag work well, but calling the function that contains the same code from other script tag doesn't.

In my code I have a google map script in the header and it works very well let's call this script tag (A).

The problem is that when I'm not in the script tag A and want to call a function that is in the script A from another script tag to reuse it. it will not work. however if I copied the code from that function and put it directly in the same tag it will work.

I want to be able to call it not to write it again. what is the wrong thing in my code??

The complete code:

<html>
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

 <script
    src="http://maps.googleapis.com/maps/api/js">
</script>
<script>
//this is the function that I want call
function getAddress(location) {
    var geocoder = new google.maps.Geocoder();
    var latLng = new google.maps.LatLng(location.lat(), location.lng());
    geocoder.geocode({
        latLng: latLng
    },
        function (responses) {
            if (responses && responses.length > 0) {
                $("#addressResult").text(responses[0].formatted_address);
                // alert(responses[0].formatted_address);
            } else {
                alert('Cannot determine address at this location.');
            }
        });
}
var map;
var myCenter = new google.maps.LatLng(51.508742, -0.120850);

function initialize() {
    var mapProp = {
        center: myCenter,
        zoom: 5,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("googleMap"), mapProp);

    google.maps.event.addListener(map, 'click', function (event) {
        placeMarker(event.latLng);

    });

}
var marker
function placeMarker(location) {
    if (marker) {
        marker.setPosition(location);
    } else {
        marker = new google.maps.Marker({
            position: location,
            map: map
        });
    }
    //calling it inside and it's working
    getAddress(location);

}

google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>


<body>
<label>Location: </label>
                    <label id="addressResult"></label>
                    <input type="button" value="Current Location" onclick="getLocation()" />
<script>
                            var x = document.getElementById("addressResult");
                        function getLocation() {
                            if (navigator.geolocation) {
                                navigator.geolocation.getCurrentPosition(showPosition);
                            } else {
                                x.innerHTML = "Geolocation is not supported by this browser.";
                            }
                        }

                        function showPosition(position) {
                           //here where I want to call it
                            getAddress(position);
                            }
</script>
  <div id="googleMap" style="width: 500px; height: 380px;"></div>

                        <div>
</body>
</html>

Upvotes: 1

Views: 181

Answers (1)

Nickolay
Nickolay

Reputation: 32073

As Ed mentioned, the problem is probably due to the fact that you put the function call directly in the <script> -- such code executes before the page has finished loading, and may break if something your code depends on is not yet available.

To fix that, put the code in a function that executes after the page is loaded. If you only care about relatively modern browsers, use the DOMContentLoaded event listener, and if you're using a JS framework it likely provides a way to do it while supporting older browsers.

(Obligatory jQuery plug: if you're using it, the syntax is $(function() { /* your code here */ });)

Update

It seems you don't convert the results from navigator.geolocation.getCurrentPosition() to a google.maps.LatLng value properly. Here's an example from the Google documentation:

navigator.geolocation.getCurrentPosition(function(position) {
  var initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);

Update #2 (from the OP): Changing showPosition as follows fixed the problem:

function showPosition(position) {
   var initialLocation = new google.maps.LatLng(
                           position.coords.latitude, 
                           position.coords.longitude);

   getAddress(initialLocation);
}

Upvotes: 1

Related Questions