<!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.
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);
});
}
Related
function showPosition() {
navigator.geolocation.getCurrentPosition(showMap, error);
}
function showMap(position) {
// Get location data
var mylatlong = position.coords.latitude + "," + position.coords.longitude;
// Set Google map source url
var mapLink = "https://maps.googleapis.com/maps/api/staticmap?center=" + mylatlong + "&size=50x50";
// Create and insert Google map
document.getElementById("embedMap").innerHTML = "<img alt='Map Holder' src='" + mapLink + "'>";
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
<input type="button" value="Add Map" onclick="showPosition()" />
<div id="embedMap">
<!--Google map will be embedded here-->
</div>
I am new to Javascript and HTML and currently testing out how to get current location and show it in google map after clicking the button. I have tried this but I still cannot get my current location in a map.
app.js
function showPosition() {
navigator.geolocation.getCurrentPosition(showMap);
}
function showMap(position) {
// Get location data
var latlong = position.coords.latitude + "," + position.coords.longitude;
// Set Google map source url
var mapLink = "https://maps.googleapis.com/maps/api/staticmap?center="+latlong+"&zoom=16&size=400x300&output=embed";
// Create and insert Google map
document.getElementById("embedMap").innerHTML = "<img alt='Google map' src='"+ mapLink +"'>";
}
index.html
<input type="button" value="Add Map" onclick="showPosition()"/>
<div id="embedMap">
<!--Google map will be embedded here-->
</div>
If you want to get your current position by using Geolocation in JavaScript and HTML, you might like to check this sample code of Google Maps API Javascript. This shows how to create a map that displays the geographic location of a user or device on a Google map, through use of their browser's HTML5 Geolocation feature. The user must consent to location sharing or else an error is shown. Read more about the W3C Geolocation standard. This will then map your coordinates to the map created by Maps JavaScript API.
Here is also a snippet of the sample code I made that geolocates the position after clicking the 'Geolocate' button. Remember to change the string YOUR_API_KEY with your own API key.
<!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>
</head>
<body>
<button id="myBtn">Geolocate</button>
<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;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 10
});
infoWindow = new google.maps.InfoWindow;
document.getElementById("myBtn").addEventListener("click", function(){
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found: ' + pos.lat + ',' + pos.lng);
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);
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
Hope this helps!
I am trying to develop a web application which allows the user to post notes (markers) on the map for others to read. It is basically placing markers on the map that consist of the subject and the message. It is accessed by clicking on a marker on the map.
Right now I am facing an issue with regards of retrieving the data from Firebase. I managed to make the application send data to Firebase (latitude and longitude for marker location on the map, and the message with the subject itself), but I am unable to take the information back in order to place a marker on the exact coordinates.
I followed many YouTube tutorials and online guides but the Firebase data won't show anywhere except for the console in Chrome.
Any clue what could be the issue? I am posting the JavaScript for he map and Firebase below so you can see how I saved message, subject, latitude and longitude to Firebase database.
Thanks
firebase.initializeApp(config);
var note = firebase.database().ref("note");
/*map*/
window.onload = getLocation;
var geo = navigator.geolocation;
function getLocation() {
if (geo) {
geo.watchPosition(displayLocation);
}
else {
alert("opps, geolocation API is not supported ");
}
}
function displayLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
/*diaplays coordinates in the footer of the webapp*/
var div = document.getElementById( 'location' );
longText = document.getElementById("longitude")
if (latitude == latitude)
{
div.innerHTML = "X: " + latitude + " Y: " + longitude;
}
}
/*map*/
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6,
disableDefaultUI: true,
});
infoWindow = new google.maps.InfoWindow;
/*gets Navigation, sets the map to current position and posts a marker*/
/*Shouldn't post a marker, code will be removed later when we learn how
to post markers to note locations rather than user locations*/
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
})
var marker = new google.maps.Marker
({
position: pos,
map: map
})
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
handleLocationError(false, infoWindow, map.getCenter());
}
}
/*stores Geolocation in local storage to call it later*/
navigator.geolocation.getCurrentPosition(function(p)
{
localStorage.setItem("latitude", p.coords.latitude);
localStorage.setItem("longitude", p.coords.longitude);
}, function(e){console.log(e)})
/*error handler obviously*/
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);
}
/*button firebase function*/
var submitNote = function () {
var subject = $("#messageSubject").val();
var message = $("#messageContent").val();
var lat = localStorage.latitude;
var lon = localStorage.longitude;
note.push({
"subject": subject,
"message": message,
"latitude": lat,
"longitude": lon
});
};
$(window).load(function () {
$("#noteForm").submit(submitNote);
});
To retrieve the latitude and longitude from the database:
firebase.database().ref().child("markers").on('value').then(function(snapshot) {
snapshot.forEach(function(child) {
var childData = child.val();
var latitudes=child.val().latitude;
var longitudes=child.val().longitude;
});
});
Assuming the database is like this:
markers
pushid
subject: subject
message: message
latitude: lat
longitude: lon
I am trying to show on one map user's current location and other users markers whose locations I get from ajax post.
In other words I am trying to combine this
https://developers.google.com/maps/documentation/javascript/examples/map-geolocation
with this
http://en.marnoto.com/2013/12/mapa-com-varios-marcadores-google-maps.html
or even the simpler version
Google Maps JS API v3 - Simple Multiple Marker Example
but I don't know how to implement my data that I get from ajax. In order to get the information from ajax I have to pass the latitude and longitude so that I can get the users that are in 1km radius and who were logged in in the past 5 minutes. I have written the query, and my api is correct,I have checked that part, but I don't know how to combine the two codes in order to get one map with user's current location and other users markers.
this is my index.html file
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Geolocation</title>
<script src="location.js"></script>
</head><body>
<div id="map"></div>
<p id="geolocation"></p>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 45.38361, lng: 20.38194},
zoomControl:true,
zoom: 15
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('You are here.');
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.');
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=myKey&callback=initMap">
</script>
</body>
and this is my location.js file
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
function onSuccess(position) {
var element = document.getElementById('geolocation');
console.log(position.coords.latitude);
console.log(position.coords.longitude);
//here is where I write in the db user's current location
$.post("url/location", {username: localStorage.getItem("username"), latitude: position.coords.latitude, longitude: position.coords.longitude});
//here is where I get other users locations based on user's current one and in the radius of 1km
$.post("url/getUsers", {latitude: position.coords.latitude, longitude: position.coords.longitude})
.done(function (data) {
$(data).each(function (index, value) {
//here I am writing in the console the data that I receive back from the ajax call, and I presume that I should make my markers here
console.log(value.username + ' ' + value.latitude + ' ' + value.longitude);
});
});
}
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
for (i = 0; i < jsonArray.locations.length; i++)
{
var counter = jsonArray.locations[i];
var infowindow = new google.maps.InfoWindow();
marker = new google.maps.Marker({
position: new google.maps.LatLng(counter['lat'], counter['lon']),
map: map,
icon:'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+i+'|FF0000|000000'
});
}
I'm trying to build a website that shows a map and on top of it I want to display a button that takes you to your current location.
I'm using Google maps service to pull out the map, I also manage to get the user location by itself so all the JavaScript seems to be working fine but when add the function getlocation to the code and try to call it from the HTML it doesn't work. I believe that is probably not finding the function and I can't figure out why?
I will leave the code below:
<script>
var map;
function initialize() {
var miami = new google.maps.LatLng(41.85, -87.65);
var mapOptions = {
zoom: 4,
center: miami,
disableDefaultUI: true,
}
map = new google.maps.Map(document.getElementById('mymap'),
mapOptions);
var myloc = document.getElementById("try");
function getlocation () {
//code
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I'm using inline style for everything. I'm somehow new into this of JavaScript so if could please tell me where is my error or what else do I need to make a button from the HTML call a function on JavaScript.
In addition here is the HTML button and map div
<style>
html, body, #mymap{
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<body>
<div id="try"><button onclick="getlocation()">Click here</button></div>
<div id="mymap"></div>
</body>
If you don't understand what my question is please also comment!
This is my first question here!
google.maps.event.addListener(map, 'click', function(event) {
marker = new google.maps.Marker({position: event.latLng, map: map});
});
I'm making a webapp that allows people to see the location of buses on Google maps. I'm having some problems with global variables in JavaScript. window.variable doesn't work for me. Neither does defining the variable outside the all the functions works. Here is my complete client side code:
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see a blank space instead of the map, this
// is probably because you have denied permission for location sharing.
var old = [];
function getLocation()
{
$.get( "http://54.86.161.214/EC_bus_app/get_location.php", function( data ) {
old=[];
var buses = data;
var number_of_buses = buses.slice(0,1);
buses = buses.slice(2);
buses = buses.slice(0,-1);
var bus_coordinates_and_numbers = buses.split(/[ ]+/);
var length_of_array = bus_coordinates_and_numbers.length;
// Turn a single dimensional array into a multi-dimensional array
for (var index = 0; index < bus_coordinates_and_numbers.length; index+= 3)
old.push( bus_coordinates_and_numbers.slice(index, index + 3) );
console.log(old);
//initialize(old);
});
}
setInterval(getLocation, 10000);
var map;
function initialize() {
var mapOptions = {
zoom: 18
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var image = "icon_97.png";
for (i=0;i<old.length; i = i + 1){
var x = old[i][0];
var y = old[i][1];
var myLatlng = new google.maps.LatLng(x,y);
var busMarker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
title: old[i][2]
});
}
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Your location'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
The variable in question is old. I can pass it to the initialize function from within the get location function using initialize(old);. However, as you can see, I'm using a timer, and initialize(old); causes the entire map to reload again and again, whereas I only want the location markers to load again and again.
Solved the problem by moving getLocation() inside initialize(). But what #geocodezip said in the comments also answers my question completely.
Your problem is not with global variables. It is with asynchronous functions. You need to initialize the map, then request data (asynchronous request), make markers on the map, then periodically update them.