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