简体   繁体   English

在脚本标签内的其他地方调用函数不起作用

[英]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).在我的代码中,我在标题中有一个谷歌地图脚本,它工作得很好,我们称之为脚本标签 (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.问题是,当我不在脚本标签 A 中并且想要从另一个脚本标签调用脚本 A 中的函数以重用它时。 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>

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.正如 Ed 所提到的,问题可能是由于您将函数调用直接放在 <script> 中——此类代码在页面加载完成之前执行,如果您的代码所依赖的某些内容尚不可用,则可能会中断。

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.如果您只关心相对现代的浏览器,请使用DOMContentLoaded事件侦听器,如果您使用的是 JS 框架,它可能提供了一种在支持旧浏览器的同时执行此操作的方法。

(Obligatory jQuery plug: if you're using it, the syntax is $(function() { /* your code here */ }); ) (强制性的 jQuery 插件:如果你正在使用它,语法是$(function() { /* your code here */ });

Update更新

It seems you don't convert the results from navigator.geolocation.getCurrentPosition() to a google.maps.LatLng value properly.看来您没有正确地将结果从navigator.geolocation.getCurrentPosition()转换为google.maps.LatLng值。 Here's an example from the Google documentation :以下是Google 文档中的一个示例

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:更新 #2(来自 OP):更改showPosition如下修复了问题:

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

   getAddress(initialLocation);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM