簡體   English   中英

如何通過使用htlm和Java腳本從Firebase數據庫檢索的緯度和經度在地圖上顯示標記

[英]How to show a marker on map by using latitude and longitude retrieved from firebase database in htlm and java script

我正在從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)); 

或者,將它們與Maps API配合使用的地方,例如

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM