如何通过使用HTLM和Java脚本中的Firebase数据库检索到的纬度和经度在地图上显示标记



我正在从firebase数据库中检索纬度和经度。值存储在变量中,即纬度和经度。但是,当我尝试使用这些值在地图上设置标记时,它不起作用,但是当我给出静态纬度和位置时,标记会出现。请帮帮我。谢谢

这是我用来检索位置并在地图上显示的HTML文件的代码。`

      <head>
            <title>Data From Firebase Database</title>
<!--<meta http-equiv="refresh" content="5" >   -->
<style>
#map{
    height: 400px;
    width: 100%;
}
</style>
</head>
<body>

<div class= ""mainDiv" align= "left">
<h1> Locations </h1>
<table>
<thead>
<tr>
<td>Latitude</td>
<td>Longitude</td>
</tr>
</thead>
<tbody id="table_body">
</tbody>
</table>
</div>
<script src= "https://www.gstatic.com/firebasejs/3.3.2/firebase.js"></script>
<script>
var config = {
apiKey: "AIzaSyCU7LWliFjX7iWtNkZHhuZI0jvih6rffFI",
authDomain: "test26sep-eae46.firebaseio.com",
databaseURL: "https://test26sep-eae46.firebaseio.com/",
storageBucket: "test26sep-eae46.appspot.com",
};
firebase.initializeApp(config);
</script>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
var rootRef = firebase.database().ref();
rootRef.on("child_added", snap =>{
var latitude = snap.child("latitude").val();
var longitude = snap.child("longitude").val();
initMap(latitude,longitude);
$("#table_body").append("<tr><td>" + latitude + "</td><td>" + longitude + "</td></tr>");
});
</script>
<h1>Map</h1>
<div id="map"></div>
    <script>
function initMap(latitude,longitude){

//alert('Values have been gathered click ok to show map !! Welcome Taj , from Arslan !! :PP');
var options = {
    zoom: 8,
        center: {lat: 31.5546,lng:74.3572}
}
var map = new google.maps.Map(document.getElementById('map'), options);

//show an alert to check if the values are being fetched from firebase database stored in latitude and longitude.
  alert (latitude + " " + longitude);

var marker = new google.maps.Marker({
        position:{lat: latitude, lng: longitude},
        map:map,
      });
      var infoWindow = new google.maps.InfoWindow({
        content:'<h4>Lahore</h4>'
      });
      marker.addListener('click', function(){
        infoWindow.open(map, marker);
      });
}
    </script>
    <script
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD0w2dY7OZvF6nBvnLLxzAzXi05l_8jc-o">

    </script>
</body>
</html>

`

所以在哪里做:

var latitude = snap.child("latitude").val();
var longitude = snap.child("longitude").val();

这些值正在从.val()返回作为字符串。您必须将它们转换为数字才能使用Google Maps。

只是做:

initMap(parseFloat(latitude), parseFloat(longitude)); 

或与地图API一起使用它们的地方,例如

position:{lat: parseFloat(latitude), lng: parseFloat(longitude)}

最新更新