c# - 使用谷歌地图的地址验证器

标签 c# javascript jquery asp.net geocode

我正在使用谷歌地图创建一个地址验证器网络应用程序。我的用户界面:

] enter image description here

现在我想要的是在按下确定按钮后,地址应该显示在您的地址中,看起来像这样的字段 701 1st, Sunnywale, CA 94089 现在我的确定按钮点击事件是

FullAddress.Text = AddressLine1.Text + ',' + ' ' + City.Text + ',' + ' ' + State.Text+ ' ' +Zip.Text;

但是当我添加 javascript 以使用我的程序调用 google maps 时,它无法正常工作,并出现错误,如示例图片。请帮帮我。 确定按钮:

<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="OK" 
            Width="62px" style="margin-left: 0px" />

验证并定位我按钮代码:

<asp:Button ID="Submit" runat="server" style="margin-left: 97px" Text="Validate &amp; Locate Me" Width="137px" />

现在 jQuery 和地理编码部分:

<script type="text/javascript">
    // The following code show execute only after the page is fully loaded
    $(document).ready(function () {
        if ($('#MyForm').exists()) {

            // Enable jQuery Validation for the form
            $("#MyForm").validate({ onkeyup: false });

            // Add validation rules to the FullAddress field
            $("#FullAddress").rules("add", {
                fulladdress: true,
                required: true,
                messages: {
                    fulladdress: "Google cannot locate this address."
                }
            });

            // This function will be executed when the form is submitted
            function FormSubmit() {
                $.submitForm = true;
                if (!$('#MyForm').valid()) {
                    return false;
                } else {
                    if ($("#FullAddress").data("IsChecking") == true) {
                        $("#FullAddress").data("SubmitForm", true);
                        return false;
                    }

                    alert('Form Valid!  Submit!');
                    // return true;   // Uncomment to submit the form.
                    return false;     // Supress the form submission for test purpose.

                }
            }

            // Attach the FormSubmit function to the Submit button
            if ($('#Submit').exists()) {
                $("#Submit").click(FormSubmit);
            }

            // Execute the ForumSubmit function when the form is submitted
            $('#MyForm').submit(FormSubmit);
        }
    });

    // Create a jQuery exists method
    jQuery.fn.exists = function () { return jQuery(this).length > 0; }

    // Position the Google Map
    function Map(elementId, geolocation) {
        var myOptions = {
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var map = new google.maps.Map(document.getElementById(elementId), myOptions);
        map.setCenter(geolocation);
    }

    // FullAddress jQuery Validator
    function FullAddressValidator(value, element, paras) {

        // Convert the value variable into something a bit more descriptive
        var CurrentAddress = value;

        // If the address is blank, then this is for the required validator to deal with.
        if (value.length == 0) {
            return true;
        }

        // If we've already validated this address, then just return the previous result
        if ($(element).data("LastAddressValidated") == CurrentAddress) {
            return $(element).data("IsValid");
        }

        // We have a new address to validate, set the IsChecking flag to true and set the LastAddressValidated to the CurrentAddress
        $(element).data("IsChecking", true);
        $(element).data("LastAddressValidated", CurrentAddress);

        // Google Maps doesn't like line-breaks, remove them
        CurrentAddress = CurrentAddress.replace(/\n/g, "");

        // Create a new Google geocoder
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'address': CurrentAddress }, function (results, status) {

            // The code below only gets run after a successful Google service call has completed.
            // Because this is an asynchronous call, the validator has already returned a 'true' result
            // to supress an error message and then cancelled the form submission.  The code below
            // needs to fetch the true validation from the Google service and then re-execute the
            // jQuery form validator to display the error message.  Futhermore, if the form was
            // being submitted, the code below needs to resume that submit.

            // Google reported a valid geocoded address
            if (status == google.maps.GeocoderStatus.OK) {

                // Get the formatted Google result
                var address = results[0].formatted_address;

                // Count the commas in the fomatted address.
                // This doesn't look great, but it helps us understand how specific the geocoded address
                // is.  For example, "CA" will geocde to "California, USA".
                numCommas = address.match(/,/g).length;

                // A full street address will have at least 3 commas.  Alternate techniques involve
                // fetching the address_components returned by Google Maps.  That code looks even more ugly.
                if (numCommas >= 3) {

                    // Replace the first comma found with a line-break
                    address = address.replace(/, /, "\n");

                    // Remove USA from the address (remove this, if this is important to you)
                    address = address.replace(/, USA$/, "");

                    // Check for the map_canvas, if it exists then position the Google Map
                    if ($("#map_canvas").exists()) {
                        $("#map_canvas").show();
                        Map("map_canvas", results[0].geometry.location);
                    }

                    // Set the textarea value to the geocoded address
                    $(element).val(address);

                    // Cache this latest result
                    $(element).data("LastAddressValidated", address);

                    // We have a valid geocoded address
                    $(element).data("IsValid", true);
                } else {
                    // Google Maps was able to geocode the address, but it wasn't specific
                    // enough (not enough commas) to be a valid street address.
                    $(element).data("IsValid", false);
                }

                // Otherwise the address is invalid
            } else {
                $(element).data("IsValid", false);
            }

            // We're no longer in the midst of validating
            $(element).data("IsChecking", false);

            // Get the parent form element for this address field
            var form = $(element).parents('form:first');

            // This code is being run after the validation for this field,
            // if the form was being submitted before this validtor was
            // called then we need to re-submit the form.
            if ($(element).data("SubmitForm") == true) {
                form.submit();
            } else {
                // Re-validate this property so we can return the result.
                form.validate().element(element);
            }
        });

        // The FullAddress validator always returns 'true' when initially called.
        // The true result will be return later by the geocode function (above)
        return true;
    }

    // Define a new jQuery Validator method
    $.validator.addMethod("fulladdress", FullAddressValidator);
</script>

    </body>
    </html>

请在按下“确定”按钮后提供帮助,完整地址未显示在“您的地址看起来像”字段中。而不是通过消息显示:此字段是必需的。如果需要更多详细信息,请提及

最佳答案

只需使用 2 个 FORMS 即可保持控制。第一个将有地址字段和确定按钮。
第二将有休息。相应地更改您的代码。它应该工作。否则,您需要分配类并将控件分组为 2 组。
我所说的 2 组是指“确定”按钮应验证其上方的字段。而“验证并找到我”按钮应该只验证“你的地址看起来像”文本框。使用 jquery,您可以想出很多方法来对控件进行分组和验证。

如果这没有解决,请同时提供 HTML 或使用 http://jsfiddle.net/

-- 编辑--
您遇到的问题是当您按确定时,它会验证其下方的字段。现在我的感觉是您使用了没有任何分组的必填字段验证器。请指定一个 ValidationGroup 属性来分隔“确定”按钮和“验证并定位我”按钮的验证条件。 如果您不知道如何使用 ValidationGroup,请告诉我。

~CJ

关于c# - 使用谷歌地图的地址验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16330184/

相关文章:

c# - 为什么 HttpPlatformHandler 不创建日志文件?

c# - View 页面上的 MVC CSS(不是_layout)不起作用

javascript - 如何跨域postMessage?

javascript - Jquery 鼠标悬停淡入/淡出(最佳实践)

jquery - 输入设定值

jquery - IE9 表具有随机行,这些行在随机列上偏移

c# - Settings.settings 中的自定义数据类型作为类数组

c# - 使用 API 检索 Google Drive 文件夹列表

javascript - 为什么我无法访问另一个文件中的变量?

javascript - 有没有一种简单的方法可以添加 struts 1.3 html styleId 属性而不触及每个元素?