I have a Google map that uses W3C geoLocation to get a persons location. I would like to know how to get the lat and lng of their initial position into a hidden field.
// Try W3C Geolocation (Preferred)
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
// Try Google Gears Geolocation
} else if (google.gears) {
browserSupportFlag = true;
var geo = google.gears.factory.create('beta.geolocation');
geo.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeoLocation(browserSupportFlag);
});
// Browser doesn't support Geolocation
} else {
browserSupportFlag = false;
handleNoGeolocation(browserSupportFlag);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag === true) {
alert("Geolocation service failed.");
initialLocation = newyork;
} else {
alert("Your browser doesn't support geolocation. We've placed you in beautiful Minneapolis.");
initialLocation = siberia;
}
map.setCenter(initialLocation);
}
Just like the approach I used in this question:
In the getCurrentPosition method:
populateInputs(initialLocation);
Where function looks like:
function populateInputs(pos) {
document.getElementById("t1").value=pos.lat()
document.getElementById("t2").value=pos.lng();
}
Where t1 and t2 are your hidden fields
Just before (the two places) you get initialLocation, you're given the lat and longitude (as: position.coords.latitude,position.coords.longitude or position.latitude,position.longitude).
just call a function to set a hidden field at that point (passing in the lat and long). Something like:
var setHiddenField = function(lat, long) {
document.forms[0].hiddenLatField.value = lat;
document.forms[0].hiddenLongField.value = long;
}
...I'm assuming only 1 form on your page, but you should be easily able to tweak this.
Related
I am trying to get the user location by using HTML5 geolocation. The lat and lng value are received successfully and I can show it on the map. I want to save the user location to use it later so I defined origin variable and I concatenated the lat and lng variables and then I assigned the concatenated value to origin. When I am trying to use the origin value later its value is undifined. Could someone please tell me when the problem is in the code. I guess the problem is very silly but I cannot solve it. I don't think the problem is related to variable scope.
Here is the code:
let map ;
// initialize the map and show it on the dashboard.
function initMap()
{
// Map options.
let options =
{
center :
{
lat : 41.015137,
lng : 28.979530
},
zoom : 12
}
// New map.
map = new google.maps.Map
(
document.getElementById('map'),
options
);
};
$(document).ready
(
function()
{
$("#order_and_show").click
(
function()
{
// Change the text of the title and the button when get order from the user.
$('#order_title').text('Cancel the order right now') ;
$('#order_and_show').text('Cancel Now') ;
// Get user location from browser using HTML geolocation.
let origin ;
// HTML5 geolocation.
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition
(
function(position)
{
let pos =
{
lat: position.coords.latitude,
lng: position.coords.longitude
} ;
origin = position.coords.latitude + ',' + position.coords.longitude ;
// Add marker.
let marker = new google.maps.Marker
(
{
position : pos,
map : map,
}
) ;
// Center the map according to user location.
map.setCenter(pos);
// Add popup window for user location information
let infoWindow = new google.maps.InfoWindow
(
{
content : '<h6>Your Location</h6>'
}
) ;
marker.addListener
(
'click',
() =>
{
infoWindow.open(map, marker) ;
}
) ;
},
function()
{
handleLocationError(true, infoWindow, map.getCenter());
}
);
}
else
{
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
// Handle Geolocation errors.
function handleLocationError(browserHasGeolocation, infoWindow, pos)
{
infoWindow.setPosition(pos);
infoWindow.setContent
(
browserHasGeolocation ? 'Error: The Geolocation service failed.' : 'Error: Your browser does not support geolocation.'
) ;
infoWindow.open(map);
}
console.log(origin) ;
}
) ;
}
) ;
The problem with your current code is that you try to access origin outside of the callback that sets it. The getCurrentPosition callback is probably executed asynchronously, thus when you try to access origin outside of the callback the callback function is not yet executed resulting in a origin value of undefined. You could use promises or async/await to solve this issue. Such a solution might look like this:
$(document).ready(function () {
const map = new google.maps.Map(
document.getElementById("map"),
{ center: { lat: 41.015137, lng: 28.979530 }, zoom: 12 }
);
function handleLocationError(infoWindow, msg) {
infoWindow.setPosition(map.getCenter());
infoWindow.setContent(msg);
infoWindow.open(map);
}
$("#order_and_show").click(async function () {
// notice the async keyword ^
$('#order_title').text('Cancel the order right now');
$('#order_and_show').text('Cancel Now');
let position, origin;
if (navigator.geolocation) {
try {
// await the position before continuing
position = await new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject);
});
let pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
origin = position.coords.latitude + ',' + position.coords.longitude;
let marker = new google.maps.Marker({position: pos, map: map});
let infoWindow = new google.maps.InfoWindow({
content: '<h6>Your Location</h6>'
});
map.setCenter(position);
marker.addListener('click', () => infoWindow.open(map, marker));
} catch (error) {
// I'm not sure how you are able to access infoWindow here since it's
// created in the try block after the error is thrown.
handleLocationError(infoWindow, 'Error: The Geolocation service failed.')
}
} else {
// Same here, you don't have access to infoWindow, since it's not created
// yet. However both the above and this are present to mimic the question
// structure.
handleLocationError(infoWindow, 'Error: Your browser does not support geolocation.');
}
// origin should be available unless geolocation isn't supported or
// getCurrentPosisiton failed to execute successfully
console.log(origin);
});
});
For more info about working with asynchronous behaviour I recommend checking out the MDN Using Promises guide.
I am not sure but I think problem seems to be with this line:
let infoWindow = new google.maps.InfoWindow({
content: "<h6>Your Location</h6>"
});
You have declared infoWindow using let keyword which is why I think it is scoped within function(position) { .. } block and which is why infoWindow is being passed to handleLocationError function. The same could be said for let pos variable. declaring your variables globally could solve the problem.
declare pos, marker and infoWindow varibles in the same line let origin; like so:
let origin, pos, marker, infoWindow;
Final Code Should look like this, hope it helps:
let map;
// initialize the map and show it on the dashboard.
function initMap() {
// Map options.
let options = {
center: {
lat: 41.015137,
lng: 28.97953
},
zoom: 12
};
// New map.
map = new google.maps.Map(document.getElementById("map"), options);
}
$(document).ready(function() {
$("#order_and_show").click(function() {
// Change the text of the title and the button when get order from the user.
$("#order_title").text("Cancel the order right now");
$("#order_and_show").text("Cancel Now");
// Get user location from browser using HTML geolocation.
let origin, pos, marker, infoWindow;
// HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
origin = position.coords.latitude + position.coords.longitude;
// Add marker.
marker = new google.maps.Marker({
position: pos,
map: map
});
// Center the map according to user location.
map.setCenter(pos);
// Add popup window for user location information
infoWindow = new google.maps.InfoWindow({
content: "<h6>Your Location</h6>"
});
marker.addListener("click", () => {
infoWindow.open(map, marker);
});
},
function() {
handleLocationError(true, infoWindow, map.getCenter());
}
);
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
// Handle Geolocation errors.
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(
browserHasGeolocation
? "Error: The Geolocation service failed."
: "Error: Your browser does not support geolocation."
);
infoWindow.open(map);
}
console.log(origin);
});
});
I work as an intern with Ruby on Rails and yesterday I had to do something with Javascript (my javascript skills ARE AWFUL, I DON'T EVEN HAVE SKILLS with IT).
I implemented current location feature in a project, but I'd like to do it another way... the thig is kinda done, take a look:
function geolocationSuccess(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var geocoder = new google.maps.Geocoder();
var latlng = {lat: latitude, lng: longitude};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[0]){
var user_address = results[0].formatted_address;
document.getElementById("current_location").innerHTML = user_address;
}else {
console.log('No results found for these coords.');
}
}else {
console.log('Geocoder failed due to: ' + status);
}
});
}
function geolocationError() {
console.log("please enable location for this feature to work!");
}
$(document).on("ready page:ready", function() {
$("#current-location").on("click", function(event) {
event.preventDefault();
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
} else {
alert("Geolocation not supported!");
}
});
});
All right, I know it all happens when I click the button with Id="current-location", but I'd like it to happen automatically when the page loads, how can I do it?
Simply insert the code you want executed inside of a $(document).ready( block:
$(document).ready(function() {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
} else {
alert("Geolocation not supported!");
}
});
On a side note, I would recommend not naming a function variable event since event is a keyword. The standard convention for passing event to a function is to use e. For example:
$('#someId').on('click', function(e) {
e.preventDefault();
//do something
});
I have recently developed a website but I haven't been able to show the current location marker on the Google map after the location was found.
You can have a look on https://www.storra.com/listings/
I have added a custom listener to the function.php based on Listify auto-locate function but didn't manage to add the marker to the map. The code is as following,
function listify_custom_autolocation() {
if ( ! ( is_front_page() || listify_is_job_manager_archive() ) ) {
return;
}
?>
<script>
var triggered = false;
jQuery(document).on( 'facetwp-loaded', function() {
if ( ! triggered ) {
var locate = jQuery( '.locate-me' );
locate.trigger( 'click' );
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(
parseFloat(coords[0]),
parseFloat(coords[1])
),
info: new google.maps.InfoWindow({
content: val.title + val.distance
})
});
}
triggered = true;
});
</script>
<?php
}
add_action( 'wp_footer', 'listify_custom_autolocation', 9999 );
Would very much appreciate if someone could guide me out.
Thank you!
You could use this one for your locate function:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var marker = new google.maps.Marker({
position: pos,
map: map,
title: 'Your position'
});
map.setCenter(pos);
}, function() {
//handle location error (i.e. if user disallowed location access manually)
});
} else {
// Browser doesn't support Geolocation
}
The following is the relevant code on the backend. I tried adding the code given by #mxlse but didn't seem to work too.
AutoLocateView.prototype.find = function() {
var cv, error, filters, success;
cv = this.collectionView;
filters = this.filters;
if (!navigator.geolocation) {
return;
}
success = function(position) {
var lat, lng;
lat = position.coords.latitude;
lng = position.coords.longitude;
cv.set({
'lat': lat,
'lng': lng
});
return $('.locate-me').removeClass('loading');
};
error = function() {
$('.locate-me').removeClass('loading');
return filters.startup();
};
navigator.geolocation.getCurrentPosition(success, error);
return this;
};
I have an asp mvc project where the user is asked for geolocalization via google maps (API), so i had to use jquery 1.7.2 and save it's coordinates, but when i try to save them via ajax request i get this error on firebug and stops all the other code.
http://i47.photobucket.com/albums/f195/warbandit69/ErrorKambi1_zpsac3979f4.png
As you can see the error is very unacurte with it's description, and here is the function on jquery that makes that call
function ReviewAtEnd() {
if (typeof (idserialF) != "undefined" && idserialF != null) {
var datax = { idjob: idjobx, latitud: Latitud, longitud: Longitud, coordinates: coordenadasGM };
var urlx = "/JOBS/PROG41/FailedItemOnSite";
$.ajax({
type: "POST",
url: urlx,
data: datax,
async: false,
success: function (data) {
mostrar_alert_ui(data.titulo, data.mensaje, 350);
if (data.success) {
AfterPassedTest();
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Failed " + urlx);
alert(xhr.responseText);
alert(thrownError);
}
});
}
}
UPDATE
Here is the google maps function i missed to show you
var Latitud;
var Longitud;
var coordenadasGM;
function showMap() {
//If HTML5 Geolocation Is Supported In This Browser
if (navigator.geolocation) {
//Use HTML5 Geolocation API To Get Current Position
navigator.geolocation.getCurrentPosition(function (position) {
//Get Latitude From Geolocation API
var latitude = position.coords.latitude;
Latitud = latitude;
//Get Longitude From Geolocation API
var longitude = position.coords.longitude;
Longitud = Longitud;
//Define New Google Map With Lat / Lon
var coords = new google.maps.LatLng(latitude, longitude);
coordenadasGM = coords;
//Specify Google Map Options
var mapOptions = {
zoom: 15,
center: coords,
mapTypeControl: true,
navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL }, mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions);
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "You Are Here!"
});
}
);
} else {
//Otherwise - Gracefully Fall Back If Not Supported... Probably Best Not To Use A JS Alert Though :)
mostrar_alert_ui("WARNING", "Geolocation API is not supported in your browser.", 350)
}
}
//Once Page Is Populated - Initiate jQuery
$(document).ready(function () {
//Show The Map
showMap();
// When The Viewing Window Is Resized
$(window).resize(function () {
//CSS Resizes Container So Lets Recall The Map Function
showMap();
});
});
Jsfiddle here -> http://jsfiddle.net/ricardojriosr/9mzss1ud/
I am using the Google maps API along with the HTML 5 geolocation API to display my position as a marker on a map. Once this marker is displayed I have a simple on marker double-click function that saves a new marker to my current position using indexedDB. Everything goes well until the Object is about to be stored, then I received the message "Uncaught DataCloneError: Failed to execute 'put' on 'IDBObjectStore': An object could not be cloned." in the console. my code is as follows:
function initialize() {
var mapProperties = { // Set the maps properties
center: new google.maps.LatLng(55.8580, -4.2590),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-overview"), mapProperties); //Display the map in the map-overview div
function NogeoLocation(e) { //A function to handle users that do not have Geolocation
if (e) {
var content = 'Error: Unfortunately the Geolocation service failed.';
} else {
var content = 'Error: Sorry, Your web browser doesn\'t support geolocation.';
}
var options = { //Error options
map: map,
position: new google.maps.LatLng(60, 105), //Set new position on Error
content: content //Display error message
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
//Using HTML5 Geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var position = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var contentString = "Here is your current location!" + "<button onclick='myBtn()'>Save</button>"
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: position,
map: map,
title: 'My House'
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
var db;
function indexedDBOk() {
return "indexedDB" in window;
}
google.maps.event.addListener(marker, 'dblclick', function () {
alert("dbl Click");
console.log(position);
if (!indexedDBOk) return;
var openRequest = indexedDB.open("idarticle_people", 1);
openRequest.onupgradeneeded = function (e) {
var thisDB = e.target.result;
if (!thisDB.objectStoreNames.contains("people")) {
thisDB.createObjectStore("people");
}
}
openRequest.onsuccess = function (e) {
console.log("running onsuccess");
db = e.target.result;
var transaction = db.transaction(["people"], "readwrite");
var store = transaction.objectStore("people");
//Define a marker
var marker = {
position: position,
map: map,
title: 'New Marker'
}
console.log(marker);
console.log("about to perform add");
//Perform the add
var request = store.put(marker, 1);
console.log("added");
request.onerror = function (e) {
console.log("Error", e.target.error.name);
//some type of error handler
}
request.onsuccess = function (e) {
console.log("Woot! Did it");
}
}
openRequest.onerror = function (e) {
//Do something for the error
}
});
map.setCenter(position);
}, function () {
NogeoLocation(true); // Refers to NogeoLocation function
});
} else {
// If the user's browser doesn't support Geolocation
NogeoLocation(false);
} //End of HTML5 GeoLocation
} // End of the function that initializes Google Maps
google.maps.event.addDomListener(window, 'load', initialize); //On page load, execute initialize()
marker can't be cloned because the object stored in the map-property contains a reference to a DOMNode(#map-overview), which can't be cloned (see:Things that don't work with structured clones).
Remove the map-property, it will not be re-usable at all because the google.maps.Map-instance will not exist when you retrieve the marker later.
I discovered that the reason for the error was to try to add an object that was not recognized to a cache.
this.storage.set ("page", HomePage);
I switched to a string and it worked
this.storage.set ("page", "HomePage");