My website loads the user's current location using GEO location and displays it on a google map when they then click a button, I want it to store the coordinates in the database.
I have already done the GEO location and displaying the coordinates on the map, I just need to take the values from JS and store them in the database inside the if(isset($_POST['newPost'])) statement
javascript
<script>
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;
// 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.');
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>
HTML
<form id="newPost" action="index.php" method="Post">
<textarea id="txtMessage" name="body"></textarea>
<hr/>
<br/>
<br/>
<div id="map" style="width:100%;height:400px;"></div>
<br/>
<button type="submit" id="postButton" name="newPost" class="Button">Post!
</button>
</form>
PHP
if(isset($_POST['newPost']))
{
DB::query('INSERT INTO heatmap(lon, lan) VALUES (:lon, :lan)',
array(':lon'=>$VAL, ':lan'=>$VAL));
}
Any help would be appreciated
Not having a way to test it, I had to make some guesses. I don't see any Markers created, so I assume you're using the map coordinates. Consider the following:
$(function() {
var map, infoWindow;
function initMap() {
map = new google.maps.Map($('#map')[0], {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 10
});
infoWindow = new google.maps.InfoWindow();
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);
}, 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);
}
$("#newPost").submit(function(e) {
e.preventDefault();
var pData = {
body: $("#txtMessage").val(),
lng: map.coords.longitude,
lat: map.coords.latitude
};
$.post($(this).attr("action"), pData);
});
});
https://jsfiddle.net/Twisty/wzvpnmh6/21/
This would create POST Data like:
{
body: "Hello World",
lat: -34.397,
lng: 150.644
}
You could also Stringify it and send it as a combined string:
var coords = JSON.Stringify({ lat: c.lat(), lng: c.lng() });
You will then get a string like: {"lat":-34.397,"lng":150.644} that can be added direct to a DB. This is up to you and will be defined by what you need to do with the data. If you need to search for specific Lat or Long, then they will store in their own columns. If you just need the geolocation, then they can be in a single column.
Hope that helps.
References:
Google Maps API function map.getCenter()
https://developers.google.com/maps/documentation/javascript/mysql-to-maps
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'm using addEventListener to add new Marker to Google Maps using angular version 6.
I get everything needed but the actual Marker icon, it does not show on the map, why?
Here is a link to a working example on developers.google.com
https://developers.google.com/maps/documentation/javascript/info-windows-to-db
private isMapInitialized = false;
private map: any;
// Here everything statrs
ngOnInit() {
this.openMapPanel();
}
// Here I get the map and everything works great!
openMapPanel() {
setTimeout(() => {
if (!this.isMapInitialized) {
this.initMap();
this.isMapInitialized = true;
}
}, 300);
}
initMap() {
var california = {lat: 37.4419, lng: -122.1419};
this.map = new google.maps.Map(document.getElementById('map'), {
center: california,
zoom: 13
});
google.maps.event.addListener(this.map, 'click', function(event) {
this.placeNewMarker(event.latLng);
});
}
placeNewMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: this.map
});
});
}
do I miss something?
It was so simple.. all I needed to do is change that line of code.
google.maps.event.addListener(this.map, 'click', function(event) {
this.placeMarker(event.latLan);
}
to
google.maps.event.addListener(this.map, 'click', (event) => {
this.placeMarker(event.latLan);
});
and of course add the function
placeNewMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: this.map
});
});
I hope it will help someone someday :-)
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 wonder whether someone may be able to help me please.
Because of loading issues, I've moved the map options code to my HTML form, rather than it being in a separate Javascript file.
The problem is that I now can't get the Geocode functionality to work. I've added my code below. I'm sure it must be something simple, but I'm a little perplexed by this. I just wondered whether it would be at all possible please that someone could let me know where I've gone wrong.
Many thanks
function geocode() {
// This is defining the global variables
var geocoder, marker;
// This is making the link with the 'Search For Location' HTML form
var form = document.getElementById('searchforlocationform');
// This is catching the forms submit event
form.onsubmit = function() {
// This is getting the Address from the HTML forms 'Address' text box
var address = document.getElementById('inputaddress').value;
// This is making the Geocoder call
getCoordinates(address);
// This is preventing the form from doing a page submit
return false;
}
}
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
},
function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
//New Code
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
//Changed 'address' to 'returnedaddress'
function updateMarkerAddress(str) {
document.getElementById('returnedaddress').value= str;
}
// This creates the function that will return the coordinates for the address
function getCoordinates(address) {
// This checks to see if there is already a geocoded object. If not, it creates one
if(!geocoder){geocoder = new google.maps.Geocoder();}
// This is creating a GeocoderRequest object
var geocoderRequest = {address: address}
// This is making the Geocode request
geocoder.geocode(geocoderRequest, function(results, status) {
// Check if status is OK before proceeding
if (status == google.maps.GeocoderStatus.OK) {
// Center the map on the returned location
map.setCenter(results[0].geometry.location);
// Check to see if we've already got a Marker object
if (!marker) {
map.setZoom(16);
marker = new google.maps.Marker({
map: map, draggable:true
});
}
// Setting the position of the marker to the returned location
marker.setPosition(results[0].geometry.location);
// Add dragging event listeners.
google.maps.event.addListener(marker, function() {
updateMarkerAddress;
});
//This fills out the 'Latitude' and 'Longitude' text boxes on the HTML form
document.getElementById('osgb36lat').value= results[0].geometry.location.lat();
document.getElementById('osgb36lon').value= results[0].geometry.location.lng();
//This allows the marker to be draggable and tells the 'Latitude' and 'Longitude' text boxes on the HTML form to update with the new co-ordinates as the marker is dragged
google.maps.event.addListener(marker,'dragend',
function() {
updateMarkerStatus;
geocodePosition(marker.getPosition());
document.getElementById('osgb36lat').value = marker.position.lat();
document.getElementById('osgb36lon').value = marker.position.lng();
});
// Update current position info.
latLng = [marker.position.lat(), marker.position.lng()].join(', ');
geocodePosition(marker.getPosition());
var point = marker.getPosition();
map.panTo(point);
}
}
)
}
<script type="text/javascript">
(function() {
window.onload = function(){
var latlng = new google.maps.LatLng(54.312195845815246,-4.45948481875007);
var options = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_RIGHT
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN,
position: google.maps.ControlPosition.TOP_LEFT
},
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.BOTTOM_LEFT
}
};
var map = new google.maps.Map(document.getElementById('map'), options);
}
})();
</script>
You seen to be trying to call updateMarkerAddress with updateMarkerAddress; and updateMarkerStatus with updateMarkerStatus;, here you are missing (/*some param*/).
What are the loading issues? Maybe if you show your html someone could help with that too.