Grabbing coordinates from Google Maps to add to a form - javascript

I'm working on a form where I want the user to enter their current location using the GPS location in google maps. I've read the Google Maps API documentation but I'm still a bit lost on how to integrate it all. I would appreciate any help, JS is still pretty new to me and it hasn't been easy to learn.
This is the code I used from Google Maps API.
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 18.2208, lng: -66.5901},
zoom: 7,
});
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('LocalizaciĆ³n encontrada.');
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=AIzaSyAwnKnBH4qxyjHYkg3QlJP46-yG_o4QkSc&callback=initMap">
</script>

Its kind of hard to answer your question since we are missing some information. Is the Google maps imported in your project with the geolocation API? You can create an account and generate a key on https://console.cloud.google.com
After that, you'll need to call the initMap() after the page is done loading by adding the following code at the end of your Javascript.
(function(){
initMap();
}());
From there, you can now get the value of the coordinates inside your initMap function and add them wherever you need them calling pos.lat and pos.lng.
infoWindow.setContent(pos.lat+' / '+pos.lng);
https://jsfiddle.net/SohRonery/q69ra78v/6/

Related

How to hide Map and Satellite labels from Google Map [duplicate]

This question already has answers here:
How to remove a MapType from google map using Google Maps Javascript V3 API?
(4 answers)
Closed 2 years ago.
I am using Google map API for my delivery website. I am using official Google Api Map code on my website to get the exact location of customer using GPS.
This is the code of Google Map
<!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>
<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: 6
});
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>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
This is the output
Screenshot
I want to hide the MAP and Satellite Labels from the Google map. How to do this?
To remove the mapTypeControl, disable the defaultUI (which includes that), add back in the zoomControl, streetViewControl and fullscreenControl (if you want them), as described in the documentation:
// disable the default User Interface
disableDefaultUI: true,
// add back fullscreen, streetview, zoom
zoomControl: true,
streetViewControl: true,
fullscreenControl: true
proof of concept fiddle
code snippet
// 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: 6,
// disable the default User Interface
disableDefaultUI: true,
// add back fullscreen, streetview, zoom
zoomControl: true,
streetViewControl: true,
fullscreenControl: true
});
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);
}
/* 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;
}
<title>Removing the MapType Control</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly" defer></script>
<div id="map"></div>

Google Map API Geolocation w/Javascript

I'm working on a project that locates coffee shops near the user's location (which is retrieved via the browser). I'm using Google Maps API with the geolocation.
My idea is to locate the users location via geolocation and then retrieve cafes nearby their location.
I can't seem to figure out how to add coffee shops or auto search and display coffee shops on the map nearby the user once the location is retrieved by the browser.
Hardcoding the locations in just doesn't seem like the solution but I was hoping to get some advice from more experienced programmers on how I could do this.
At the moment, the code for the map is taken from Google Maps documentation as it provides the functionality I need other than the searching.
I've pasted it below.
function mapFunc() {
// referenced from google maps api documentation
var map;
var infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 15
});
infoWindow = new google.maps.InfoWindow;
//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!');
infoWindow.open(map);
map.setCenter(pos);
}, function () {
handleLocationError(true, infoWindow, map.getCenter());
search();
});
} 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);
}
//get coffee shops nearby??
}
mapFunc();
You need to use the places library in of Google Map api.
Include it in in tag as below
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
Then use something like the sample code below:
var map;
var service;
var infowindow;
function initialize() {
//replace the lat long with results from your geocoding function
var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: '500', //radius in metres
type: ['coffee shops']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
see details in https://developers.google.com/maps/documentation/javascript/places#place_search_requests

Google Maps geolocation API store on .click

I am fairly new to Google Maps API and not very experienced in JS. I've got some questions on geolocations. What I am trying to achieve: a user's current geolocation should be saved onclick, displayed on map and stored on clientside, so that it can be navigated to in later steps. The code below in its current state shows the geolocation of a user in an (InfoWindow) as the map is rendered for the first time.
Any hints on how to achieve what I am planning to do?
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 18
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Geolocation in HTML
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.');
}

Get current user location and other users markers on same map using HTML, AJAX and JS

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'
});
}

Google Maps API identical examples: one renders, one doesn't

Here are two jsfiddles with identical code. One is a fork from Google Maps API's documentation, no changes. The second is just copied and pasted into jsfiddle. The fork from Google renders as expected. The one I copied and pasted does not.
I used a diff checker, and it showed them as identical. What am I missing?
HTML
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDglJmtJY5078jjZOJZFNNMO7CJb5E3nE4&callback=initMap">
</script>
JS
// 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.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
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('Location found.');
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.');
}
CSS
/* 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;
}
In your second fiddle, the JAVASCRIPT settings needs to have Load Type as No wrap - in <body>

Categories

Resources