在javascript中从数据库下载坐标时,谷歌地图未显示

Google map not showing while downloading coordinates from database in javascript

本文关键字:谷歌地图 显示 坐标 下载 javascript 数据库      更新时间:2023-09-26

我有一个小应用程序,我不断从数据库下载地理坐标,并在地图中显示,同时上传地理位置坐标。我已经写了代码,数据上传和下载都很好。但是地图本身根本没有显示出来。这是我的代码:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en&key=MY-API-KEY" async defer></script>
<script>

if ("geolocation" in navigator) 
{
    request_location();
} 
// Requesting location from user
function request_location()
{
    // Will repeat the process in two minutes
    setTimeout(request_location, 500 * 1000);
    // Get location info from browser and pass it to updating function
    navigator.geolocation.getCurrentPosition(update_location);
}
// Sending location to server via POST request
function update_location(position)
{
    // For simplicity of example we'll 
    // send POST AJAX request with jQuery
    $.post( "functions.php?action=update_geolocation", { latitude: position.coords.latitude, longitude: position.coords.longitude });

}
function updatemap(lat_coordinates, long_coordinates)
{

        var map = new google.maps.Map(document.getElementById('mapholder'), 
            {
            zoom: 4,
                center: {lat: lat_coordinates, lng: long_coordinates},
        });
        var marker = new google.maps.Marker({
            position: {lat: lat_coordinates, lng: long_coordinates},
                map: map,
                title: 'Hello World!'
                    });
 }

setInterval(function update_map(){
        jQuery.ajax({
            url: "http://dev.radiumenterprises.co.uk/viitgo/provider/rest.php/geolocation",
            type: "GET",
            contentType: 'application/json; charset=utf-8',
            success: function(resultData) {
                            console.log(resultData);
                            console.log(resultData.latitude);
                            console.log(resultData.longitude);
                            var lat_coordinates = parseFloat(resultData.latitude)
                            var long_coordinates = parseFloat(resultData.longitude)
                            updatemap(lat_coordinates, long_coordinates); 

            },
            error : function(jqXHR, textStatus, errorThrown) {
            },
        });
    }, 3000);
    </script>
    <div style="height:100%; width:100%;">
    <div style="margin: 0;padding: 0;height: 100%;" id="mapholder"></div>
    </div>

有人看到我哪里出错了吗?我唯一的问题是地图本身没有显示。我已经尝试了很多解决方案,但不知道是什么原因造成的。任何建议都将不胜感激。提前谢谢。

您对/rest.php/geolocation的请求似乎超时了,因此永远不会调用updatemap。

如果请求对你有效,那么检查你的mapholderdiv的尺寸。它的高度似乎为0。

用于渲染贴图的js代码似乎是正确的。

检查平台坐标,提供的lng_coordinates是否正确。

也可以尝试在$(document).ready(function(){})中添加js,或者确保js在html代码之后呈现。

当呈现js时,DOM元素可能不可用。