【问题标题】:How to add an AJAX request into Google Map JS code如何将 AJAX 请求添加到 Google Map JS 代码中
【发布时间】:2018-01-17 19:06:59
【问题描述】:

我正在尝试传递从用户搜索的位置获得的纬度和经度值(请参阅屏幕截图以获取示例)并将它们传递给我的 Spring MVC 框架中的控制器类。 (我打算将纬度和经度值与 MySQL 数据库中的其他纬度和经度值进行比较)。它将根据用户搜索的位置将评分返回到下面的文本字段框中。由于不熟悉这种类型的多语言交流,我做了一些研究,似乎 AJAX 可以用于我想要实现的目标。但是,我遇到了如何将其集成到下面的 JS 代码中的麻烦。

基本上发生的是“定位”按钮调用 JS 函数,该函数将搜索位置并计算纬度和经度。我有点不清楚当按下相同的“定位”按钮时,AJAX 请求是否可以将相同的纬度和经度值传递给控制器​​类?

index.html

//I've omitted snippets of irrelevant code for conciseness


<script>
var geocoder;
var map;
var marker;

/*
 * Google Map with marker
 */
function initialize() {
    var initialLat = $('.search_latitude').val();
    var initialLong = $('.search_longitude').val();
    initialLat = initialLat?initialLat:53.350140;
    initialLong = initialLong?initialLong:-6.266155;

    var latlng = new google.maps.LatLng(initialLat, initialLong);
    var options = {
        zoom: 11,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("geomap"), options);

    geocoder = new google.maps.Geocoder();

    marker = new google.maps.Marker({
        map: map,
        draggable: true,
        position: latlng
    });

    google.maps.event.addListener(marker, "dragend", function () {
        var point = marker.getPosition();
        map.panTo(point);
        geocoder.geocode({'latLng': marker.getPosition()}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                marker.setPosition(results[0].geometry.location);
                $('.search_addr').val(results[0].formatted_address);
                $('.search_latitude').val(marker.getPosition().lat());
                $('.search_longitude').val(marker.getPosition().lng());
            }
        });
    });

}

$(document).ready(function () {
    //load google map
    initialize();

    /*
     * autocomplete location search
     */
    var PostCodeid = '#search_location';
    $(function () {
        $(PostCodeid).autocomplete({
            source: function (request, response) {
                geocoder.geocode({
                    'address': request.term
                }, function (results, status) {
                    response($.map(results, function (item) {
                        return {
                            label: item.formatted_address,
                            value: item.formatted_address,
                            lat: item.geometry.location.lat(),
                            lon: item.geometry.location.lng()
                        };
                    }));
                });
            },
            select: function (event, ui) {
                $('.search_addr').val(ui.item.value);
                $('.search_latitude').val(ui.item.lat);
                $('.search_longitude').val(ui.item.lon);
                var latlng = new google.maps.LatLng(ui.item.lat, ui.item.lon);
                marker.setPosition(latlng);
                initialize();
            }
        });
    });

    /*
     * Point location on google map
     */
    $('.get_map').click(function (e) {
        var address = $(PostCodeid).val();
        geocoder.geocode({'address': address}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                marker.setPosition(results[0].geometry.location);
                $('.search_addr').val(results[0].formatted_address);
                $('.search_latitude').val(marker.getPosition().lat());
                $('.search_longitude').val(marker.getPosition().lng());
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
        e.preventDefault();
    });

    //Add listener to marker for reverse geocoding
    google.maps.event.addListener(marker, 'drag', function () {
        geocoder.geocode({'latLng': marker.getPosition()}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    $('.search_addr').val(results[0].formatted_address);
                    $('.search_latitude').val(marker.getPosition().lat());
                    $('.search_longitude').val(marker.getPosition().lng());
                }
            }
        });
    });
});

geocoder.geocode({
    'address': request.term,
    componentRestrictions: {country: "ie"}
})

function loginAlert(){
    alert("User must be logged in to view reports");
}
</script>
</head>
<body>

<h3>Area Rating System</h3>
    <h5>Please register with a valid Username and password below!</h5>
    <form action="#" th:action="@{/}" th:object="${user}" method="post">
        <table>

            <tr>
                <td>Username &nbsp;  </td>
                <td><input type="text" th:field="*{username}" />&nbsp; &nbsp;</td>

                <td>Password  &nbsp;</td>
                <td><input type="password" th:field="*{password}" />&nbsp; &nbsp;</td>

                <td><button type="submit">Register</button>&nbsp; &nbsp;</td>
                <td><a href = "login.html">Already registered? Log in here</a></td>
            </tr>
            <tr>
            </tr>
        </table>
    </form>
    <br></br>


<form>
<div class="form-group input-group">
    <input type="text" id="search_location" class="form-control" placeholder="Search location"/>
    <div class="input-group-btn">
        <button class="btn btn-default get_map" type="submit">
            Locate
        </button>
    </div>
</div>
</form>

<!-- display google map -->
<div id="geomap"></div>

<div id="forminputs">
<table>
<tr>
<!-- display selected location information -->
<th>
<h4>Location Details</h4>
<p>Address: &nbsp; &nbsp;<input type="text" class="search_addr" size="45"/></p>
<p>Latitude: &nbsp; &nbsp;<input type="text" class="search_latitude" size="30"/></p>
<p>Longitude: <input type="text" class="search_longitude" size="30"/></p>
<p style = "height: 120px"></p>

</th>
<th style = "width: 100px">  </th>
<th>
<h4>Area Rating</h4>
<p>Average House Price: <input type="text"  size="10"/>&nbsp; &nbsp; &nbsp;<a href="#" onClick="loginAlert();">Full Report</a></p>
<p>Crime Rating: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text"  size="10"/>&nbsp; &nbsp; &nbsp;<a href="#" onClick="loginAlert();">Full Report</a></p>


</tr>
</table>
</div>
</body>

</html>

【问题讨论】:

    标签: javascript ajax spring google-maps


    【解决方案1】:

    我不会做jQuery,但我可以尝试给你使用JS的方法。但是,我从未使用过 Spring MVC,所以我将给出我将如何使用 PHP 进行 MySQL 更新的答案。希望这可以为您提供一些想法,以便您可以根据您选择的语言推断出您需要什么。

    现在您已经有了所需的值:

    var Lat = $('.search_latitude').val();
    var Long = $('.search_longitude').val();
    

    您想在按下“定位”按钮时运行 AJAX 函数,以便您可以像这样将纬度和经度值发送到您的 MySQL:

    <button class="btn btn-default get_map" type="submit" onclick="sendLatLong();">
            Locate
        </button>
    
    <script>
    function sendLatLong() {
    var xhr = new XMLHttpRequest(); // Create our XMLHttpRequest object
    
    var url = "toMySQL.php"; // This PHP file will query the database (MySQL)
                             // and do the comparison you want.
    
    var coor = "lat="+Lat+"&long="+Long;
    xhr.open("POST", url, true);
    
    // Set content type header information for sending url encoded variables in the request
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    
    // Access the onreadystatechange event for the XMLHttpRequest object
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == 200) {
            var return_data = xhr.responseText;
            // For simplicty I just return whatever result into a <DIV id="status">
            // You may populate other input fields with your data 
            document.getElementById("status").innerHTML = return_data;
        }
        // Send the data to PHP now... and wait for response to update the status div
        xhr.send(coor);
        document.getElementById("status").innerHTML = "processing...";
    }
    </script>
    

    现在 PHP 文件“toMySQL.php”查询数据库表并根据您刚刚发送的变量进行比较并返回结果。

    如果您需要任何进一步的说明,请告诉我。 祝你好运!

    【讨论】:

    • 我以前也没有使用过 PHP,但我认为这会让我朝着正确的方向前进。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    相关资源
    最近更新 更多