简体   繁体   中英

geocoder.geocode works only in particular condition

This code works only with the 2 alerts active in the script block, if you comment the first or the second alert the geocode function doesn't work. It is a simple asp.net page that try to obtain latitude and longitude from an address, in this case hard coded:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="/Global/js/jquery-1.8.3.min.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div style="width: 100%">
            <div style="width: 50%; clear: left; float: left; text-align: right;">
                Latitudine:
            </div>
            <div style="width: 50%; float: left; text-align: left;">
                <asp:TextBox ID="TxbLatitudine" runat="server" Columns="20"  />
                <asp:Button ID="BtnFind" runat="server" Text="Cerca cordinate" OnClientClick="javascript: findLocation();" />
            </div>
        </div>
        <div style="width: 100%">
            <div style="width: 50%; clear: left; float: left; text-align: right;">
                Longitudine:
            </div>
            <div style="width: 30%; float: left; text-align: left;">
                <asp:TextBox ID="TxbLongitudine"  runat="server" Columns="20" ></asp:TextBox>
            </div>
        </div>
    </form>
    <script type="text/javascript">
        function findLocation() {
            var geocoder = new google.maps.Geocoder();

            alert("before");  //if you remove this doesn't work
            geocoder.geocode({ 'address': "Cagliari, Italy" }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    $('#<%= TxbLatitudine.ClientID %>').val("a");
                } else {
                    $('#<%= TxbLongitudine.ClientID %>').val("not OK");
                }
            });
            alert("after");  //if you remove this doesn't work
        }
    </script>
</body>
</html>

I replaced the asp:Button with html input button:

<input id="Button1" type="button" value="Find..." onclick="javascript: findLocation();" />

the first one caused page postback that interfered with the client script block function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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