-2

<!DOCTYPE html>
<html>
  <head>
    <title>Geolocation</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
    <!-- Place this inside the HTML head; don't use async defer for now -->

    
<script src="https://www.gstatic.com/firebasejs/4.12.1/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/geofire/4.1.2/geofire.min.js"></script>

  <script>
        
        var config = {
    apiKey: "",
    authDomain: "carrier-35d7c.firebaseapp.com",
    databaseURL: "https://carrier-35d7c.firebaseio.com",
    projectId: "carrier-35d7c",
    storageBucket: "carrier-35d7c.appspot.com",
    messagingSenderId: "827792028763"
  };
        if (!firebase.apps.length) {
            firebase.initializeApp(config);
        }
        
        //Create a node at firebase location to add locations as child keys
        var locationsRef = firebase.database().ref("locations");
        
        // Create a new GeoFire key under users Firebase location
        var geoFire = new GeoFire(locationsRef.push());
      </script>


  </head>
  <body>
    <div id="map"></div>
    <script>
      // Note: This example requires that you consent to location sharing when
      // prompted by your browser. If you see the error "The Geolocation service
      // failed.", it means you probably did not give permission for the browser to
      // locate you.
      var map, infoWindow;
      var lat, lng;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 18
          //mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        infoWindow = new google.maps.InfoWindow;
        // Try HTML5 geolocation.
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            lat = position.coords.latitude;
            lng = position.coords.longitude;
            var pos = {lat: lat, lng: lng };
                _setGeoFire();
              var locationsRef = firebase.database().ref("locations");
locationsRef.on('child_added', function(snapshot) {
  var data = snapshot.val();
  var markerLabel = document.cookie;
  var marker = new google.maps.Marker({
    position: {
      lat: data.User.l[0],
      lng: data.User.l[1]
    },
    map: map,
    label: markerLabel
  });
  bounds.extend(marker.getPosition());
  marker.addListener('click', (function(data) {
    return function(e) {
      infowindow.setContent(this.getPosition().toUrlValue(6) + "<br>" + data.User.g);
      infowindow.open(map, this);
    }
  }(data)));
  map.fitBounds(bounds);
});
          
            infoWindow.setPosition(pos);
            infoWindow.setContent('Current Location');
            infoWindow.open(map);
            map.setCenter(pos);
          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
          });
        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, infoWindow, map.getCenter());
        }
      }
      function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
                              'Error: The Geolocation service failed.' :
                              'Error: Your browser doesn\'t support geolocation.');
        infoWindow.open(map);
      }
      function _setGeoFire(){
    geoFire.set("User", [lat, lng]).then(()=>{
            console.log("Location added");
        }).catch(function(error) {
            console.log(error);
        });
}
    </script>
    <script 
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD2nPlSt_nM7PSKD8So8anbUbBYICFWcCA&callback=initMap">
    </script>
  </body>
</html>

I'm using google maps API to display the user current location on a map. Everytime the user refreshes the page, it creates a new marker with the user's current location but it leaves the old one there also. I want the old marker to be deleted everytime the user refreshes the page so that there is only one marker per user instead of like 50. Ive tried using this code.

if (marker&& marker.setPosition) {
    // marker exists, move it
    marker.setPosition(lat,lng);
} else { 
// create the marker
    marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        
    });
}

I can't seem to get this to work. If anyone could help me with this I would really appreciate it.

enter image description here

BIlly BOB
  • 25
  • 4
  • 1
    On each page refresh you are pushing new location to your database and than you are read those values back. When you refresh page, browser data is gone (no markers, no google map). The problem is not with markers, but with adding location everytime page is refreshed. Also, maybe you don't want to post your google api keys map quota is kind of valuable resource. – bojan May 15 '18 at 22:12
  • So How would I delete the old location every time the page is refreshed if you are saying its a problem with adding location everytime the page is refreshed? thanks for the helo – BIlly BOB May 15 '18 at 22:20

1 Answers1

0

It really depends on what you are trying to achieve. You can delete that location when user will close or refresh browser. For example:

//Create a node at firebase location to add locations as child keys
  var locationsRef = firebase.database().ref("locations");
  var pushRef = locationsRef.push()
// Create a new GeoFire key under users Firebase location
// replace var geoFire = new GeoFire(locationsRef.push()); with
var geoFire = new GeoFire(pushRef); 

later in your code:

function _setGeoFire(){
geoFire.set("User", [lat, lng]).then(()=>{
  console.log("Location added");
  pushRef.child("User").onDisconnect().remove();
}).catch(function(error) {
  console.log(error);
});
}
bojan
  • 870
  • 9
  • 7
  • Where exactly would I put that code? I am trying to delete the old marker when the page is refreshed – BIlly BOB May 16 '18 at 03:36
  • I have edited my answer pointing where you want to change your code – bojan May 16 '18 at 12:41
  • Now the markers is not showing up to display where all the other uses are – BIlly BOB May 16 '18 at 16:41
  • Sorry, but I don't really know what you want to achieve here. – bojan May 16 '18 at 17:39
  • My original code used to display all the current users locations on a map with markers for every user. Everytime I refreshed the page it would create a new marker for the user but leave the old one also. All I wanted was for the old marker to be deleted when I refreshed your page and I tried you code and now none of the markers are not showing up. Im gonna upload a picture of what my app originally did. – BIlly BOB May 16 '18 at 19:04