I am creating a webpage, in which it first get user location & then update map with user current location by showing a marker to user where he is now. But i want to get user location continuously after 500 milliseconds, But it is showing popup to user again & again to allow his location. But i want that if a user allow previous then popup will not shown to him again. Below is my for that.
<html>
<head>
<title>Map with live marker</title>
<meta name="viewport" content="initial-scale=1.0">
</head>
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<body>
<div id="map"></div>
<script>
var lat=0;
var lng=0;
var map;
function getUserlocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
lng = position.coords.longitude;
// initMap();
console.log(lat,lng);
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
function initMap() {
var myLatLng = {lat: lat, lng: lng};
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: lat, lng: lng},
zoom: 30
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
setInterval(function(){
getUserlocation();
},500);
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=Apikey"></script>
</body>
</html>
Can anyone please help me to solve this issue?
I was thinking of something like this:
Didn't test it let me know if it works ;-)
<html>
<head>
<title>Map with live marker</title>
<meta name="viewport" content="initial-scale=1.0">
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
var marker;
if (navigator.geolocation) {
// watch for user movement
navigator.geolocation.watchPosition(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
console.log(lat,lng);
var myLatLng = {lat: lat, lng: lng}
initMap(myLatLng);
});
} else {
alert("Geolocation is not supported by this browser.");
}
function initMap(myLatLng) {
// create the map if it doesn't exist yet
if(!map) {
map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
zoom: 30
});
}
// optional for centering the map on each user movement:
else {
map.setCenter(myLatLng)
}
// create the marker if it doesn't exist yet
if(!marker) {
marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
} else {
// update the markers position
marker.setPosition(myLatLng);
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=Apikey"></script>
</body>
</html>
EDIT
Just tested it and had the same problem than you, when just drag and dropping the html file into the browser. It seems, that the browser doesn't set the permission for a local file.
Running a local web server like serve solves the problem.
Related
I am making a webpage with Google Maps API but I am getting "google not defined error"
How can I get rid of this?
How can I import Google or do something to make this piece of code work?
I want a program in which user will enter location and it shows marker there. but it is not working properly.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<h1>Perform Google Maps Search</h1>
<h3> Please enter the place you want to search</h3>
<input type="text" id="mapsearch" size="50"> <br>
<br>
<div id="map"></div>
<script>
var map;
function initMap() {
var myOptions = {
zoom:14,
navigationControl: true,
scaleControl: true,
panControl: true,
center: new google.maps.LatLng(43.6532,-79.3832),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'),myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(43.6532,-79.3832),
title:"Toronto"
});
marker.setMap(map);
}
var searchBox = new google.maps.places.SearchBox(document.getElementById('mapsearch'));
map.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById('mapsearch'));
google.maps.event.addListener(searchBox, 'places_changed', function() {
searchBox.set('map', null);
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
(function(place) {
var marker = new google.maps.Marker({
position: place.geometry.location
});
marker.bindTo('map', searchBox, 'map');
google.maps.event.addListener(marker, 'map_changed', function() {
if (!this.getMap()) {
this.unbindAll();
}
});
bounds.extend(place.geometry.location);
}(place));
}
map.fitBounds(bounds);
searchBox.set('map', map);
map.setZoom(Math.min(map.getZoom(),12));
});
google.maps.event.addDomListener(window, 'load', init);
</script>
<script src="https://maps.googleapis.com/maps/api/js?key="Your_API_Key"&callback=initMap"
async defer></script>
</body>
</html>
initMap function should be closed at last you are closing it before
var searchBox = new google.maps.places.SearchBox(document.getElementById('mapsearch'));
So you are getting google undefined error.
Also you have add parameter &libraries=places to google map script src
working example
https://plnkr.co/edit/ngtGvuhDDZAnovwPnPXh?p=preview
// Code goes here
var map;
function initMap() {
var myOptions = {
zoom:14,
navigationControl: true,
scaleControl: true,
panControl: true,
center: new google.maps.LatLng(43.6532,-79.3832),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'),myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(43.6532,-79.3832),
title:"Toronto"
});
marker.setMap(map);
var searchBox = new google.maps.places.SearchBox(document.getElementById('mapsearch'));
map.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById('mapsearch'));
google.maps.event.addListener(searchBox, 'places_changed', function() {
searchBox.set('map', null);
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
(function(place) {
var marker = new google.maps.Marker({
position: place.geometry.location
});
marker.bindTo('map', searchBox, 'map');
google.maps.event.addListener(marker, 'map_changed', function() {
if (!this.getMap()) {
this.unbindAll();
}
});
bounds.extend(place.geometry.location);
}(place));
}
map.fitBounds(bounds);
searchBox.set('map', map);
map.setZoom(Math.min(map.getZoom(),12));
});
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<h1>Perform Google Maps Search</h1>
<h3> Please enter the place you want to search</h3>
<input type="text" id="mapsearch" size="50"> <br>
<br>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAtaKPvRV8-ciYtnnzG3QI3CO7m4HJyhaI&libraries=places&callback=initMap"
async defer></script>
</body>
</html>
Most likely your google APIs have not loaded, when your script needs them - hence the "google not defined error". Move this before your script and drop the async defer - or do your script inside a "$( document ).ready"
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAtaKPvRV8-ciYtnnzG3QI3CO7m4HJyhaI&callback=initMap"
async defer></script>
I have been trying to put together two of the functionalities the GoogleMaps API offers for developers(Places Search and Geolocation)
Since I'm not very familiar with javascript, I'm not positive what could be the mistake I'm making. So far, the Places Search is totally functional (with a predetermined location) but not so the Geolocation (which should overwrite the predetermined location with the user's location).
Here you can take a look at my code.
<!DOCTYPE html>
<html>
<head>
<title>Place searches</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map {
height: 580px;
width: 680px;
border: 10px solid darkred;
padding: 5px;
margin: 25px;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var map;
var infowindow;
function initMap() {
var pyrmont = {lat:43.364490, lng:-8.407406};
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
infowindow = new google.maps.InfoWindow({map:map});
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 2000,
type: ['gym']
}, callback);
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.');
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
</script>
</head>
<body>
<header>
<h1>Encuentra tu gimnasio más próximo</h1>
</header>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=***MY_KEY***&libraries=places,geometry&callback=initMap" async defer></script>
</body>
</html>
Any help would be very much appreciated.
There seems te be an error with the casing of the infoWindow variable.
It's declared like this:
var infowindow;
But in the callback for navigator.geolocation.getCurrentPosition is used with different casing:
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
This error should have been shown in the browser's development tools console.
I'm building JS app.Tasks are:
1.Locate me and find nearest ATMs of specified bank
2.Then sort what she found in list.Sort by distance from me.
3.On the end are some design like a image on marker of store etc..
Well I did to locate me and to show me locations of ATMs
But I can't figure out to create list and sort that ATMs by distance from me
Does someone can help me
My code is
<!DOCTYPE html>
<html>
<head>
<title>Place searches</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>
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var map;
var infowindow;
function initMap() {
var pyrmont = {lat: -33.867, lng: 151.195};
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
type: ['store']
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
</script>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCW8gRR1ITJDx4F-rVpkBSetftu32XO2P0&libraries=places&callback=initMap" async defer></script>
Thanks
Just as the title states. I have tried google.maps.places.RankBy.PROMINENCE (default) and setting the radius to 50000 and am returned 20 results. But when I try the exact same search, minus the radius as according to the documentation, and using google.maps.places.RankBy.DISTANCE I am only returned 3 results in a short radius of my locations. Can someone explain why this happens and how to get a nearby search by distance with full results. Maybe I am just doing something wrong. Thanks.
The code bellow returns 20 results using google.maps.places.RankBy.PROMINENCE
var map;
var infowindow;
function initMap() {
var location = {lat: 43.139387, lng: -80.264425};
map = new google.maps.Map(document.getElementById('map'), {
center: location,
zoom: 9
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: location,
radius: 50000,
types: ['police'],
// rankBy: google.maps.places.RankBy.DISTANCE
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
<!DOCTYPE html>
<html>
<head>
<title>Place searches</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&signed_in=true&libraries=places&callback=initMap" async defer></script>
</body>
</html>
The code bellow returns only 3 results when using google.maps.places.RankBy.DISTANCE
var map;
var infowindow;
function initMap() {
var location = {lat: 43.139387, lng: -80.264425};
map = new google.maps.Map(document.getElementById('map'), {
center: location,
zoom: 9
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: location,
// radius: 50000,
types: ['police'],
rankBy: google.maps.places.RankBy.DISTANCE
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
<!DOCTYPE html>
<html>
<head>
<title>Place searches</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&signed_in=true&libraries=places&callback=initMap" async defer></script>
</body>
</html>
The radius attribute for the PROMINENCE code may have an effect on the search result. And based on the Places documentation, it can be affected by Google's index, global popularity, etc.
For DISTANCE, the optional attributes such as keyword, name, and types are now required.
Hope this clarifies some points regarding your issue.
Dear all i am a newbie to Google Maps API. I have a parsed a KML layer in Google Maps API using GeoXML3. Now how do i fetch placement marker value(Name of the place) of KML in Google Maps API onclick. Like when a kml layer gets loaded on google maps and i am clicking on any marker i should be able to fetch the placement value of the marker in an alert box. Please find the code that helps me parse a kml on google maps api. Please guide.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>KML Layer</title>
<link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript">
function initialize()
{
var chicago = new google.maps.LatLng(75.602836700999987,32.261890444473394);
var myOptions = {
zoom: 2,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP }
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//var transitLayer = new google.maps.TransitLayer();
//transitLayer.setMap(map);
var geoXml = new geoXML3.parser({map: map, singleInfoWindow: true});
geoXml.parse('kmload.kml');
var geoXml1 = new geoXML3.parser({map: map, singleInfoWindow: true});
geoXml1.parse('lines.kml');
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>
Is this what you are looking for? I have added the alert in the onclick function which displays me the name of the placemark in the alert box. Please check and let me know if you find any issues.
<!DOCTYPE>
<html>
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/trunk/ProjectedOverlay.js"></script>
<title>KML Placement Value Test</title>
<style>
html, body, #map_canvas {
height: 100%;
margin: 0;
padding: 0;
}
#panel {
top: 5px;
left: 85%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
.infowindow * {font-size: 90%; margin: 0}
</style>
<script type="text/javascript" >
geocoder = new google.maps.Geocoder();
var geoXml = null;
var geoXmlDoc = null;
var map = null;
var myLatLng = null;
var myGeoXml3Zoom = true;
var marker = [];
var polyline;
function initialize()
{
myLatLng = new google.maps.LatLng(37.422104808,-122.0838851);
var test;
var lat = 37.422104808;
var lng = -122.0838851;
var zoom = 18;
var maptype = google.maps.MapTypeId.ROADMAP;
if (!isNaN(lat) && !isNaN(lng))
{
myLatLng = new google.maps.LatLng(lat, lng);
}
var myOptions = {zoom: zoom,center: myLatLng,mapTypeId: maptype};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
infowindow = new google.maps.InfoWindow({});
geoXml = new geoXML3.parser({map: map,infoWindow: infowindow,singleInfoWindow: true,zoom: myGeoXml3Zoom, markerOptions: {optimized: false},createMarker: createMarker});
geoXml.parse('test.kml');
};
var createMarker = function (placemark, doc) {
var markerOptions = geoXML3.combineOptions(geoXml.options.markerOptions, {
map: geoXml.options.map,
position: new google.maps.LatLng(placemark.Point.coordinates[0].lat, placemark.Point.coordinates[0].lng),
title: placemark.name,
zIndex: Math.round(placemark.Point.coordinates[0].lat * -100000)<<5,
icon: placemark.style.icon,
shadow: placemark.style.shadow
});
// Create the marker on the map
var marker = new google.maps.Marker(markerOptions);
if (!!doc) {
doc.markers.push(marker);
}
// Set up and create the infowindow if it is not suppressed
if (!geoXml.options.suppressInfoWindows) {
var infoWindowOptions = geoXML3.combineOptions(geoXml.options.infoWindowOptions, {
content: '<div class="geoxml3_infowindow"><h3>' + placemark.name +
'</h3><div>' + placemark.description + '</div></div>',
pixelOffset: new google.maps.Size(0, 2)
});
if (geoXml.options.infoWindow) {
marker.infoWindow = geoXml.options.infoWindow;
} else {
marker.infoWindow = new google.maps.InfoWindow(infoWindowOptions);
}
marker.infoWindowOptions = infoWindowOptions;
// Infowindow-opening event handler
google.maps.event.addListener(marker, 'click', function()
{
alert(placemark.name);
this.infoWindow.close();
marker.infoWindow.setOptions(this.infoWindowOptions);
this.infoWindow.open(this.map, this);
});
}
placemark.marker = marker;
return marker;
};
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="float: left; width: 70%; height: 100%;"></div>
</body>
</html>
If you use the "afterParse" function to add click listeners to the markers, you can access the data (if you use function closure), example accessing the name:
// assign "useTheData" as the after parse function
var geoXml = new geoXML3.parser({map: map, singleInfoWindow: true, afterParse: useTheData});
geoXml.parse('kmload.kml');
// function to retain closure on the placemark and associated text
function bindPlacemark(placemark, text) {
google.maps.event.addListener(placemark,"click", function() {alert(text)});
}
// "afterParse" function, adds click listener to each placemark to "alert" the name
function useTheData(doc) {
for (var i = 0; i < doc[0].placemarks.length; i++) {
var placemark = doc[0].placemarks[i].polygon || doc[0].placemarks[i].marker || doc[0].placemarks[i].polyline;
bindPlacemark(placemark, doc[0].placemarks[i].name);
}
};
working example
hope it can help ;)
/**
* map
*/
var myLatlng = new google.maps.LatLng(39.980278, 4.049835);
var myOptions = {
zoom: 10,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
}
var map = new google.maps.Map(document.getElementById('mapa'), myOptions);
var infoWindow = new google.maps.InfoWindow();
var markerBounds = new google.maps.LatLngBounds();
var markerArray = [];
function makeMarker(options){
var pushPin = new google.maps.Marker({map:map});
pushPin.setOptions(options);
google.maps.event.addListener(pushPin, 'click', function(){
infoWindow.setOptions(options);
infoWindow.open(map, pushPin);
});
markerArray.push(pushPin);
return pushPin;
}
google.maps.event.addListener(map, 'click', function(){
infoWindow.close();
});
function openMarker(i){
google.maps.event.trigger(markerArray[i],'click');
};
/**
*markers
*/
makeMarker({
position: new google.maps.LatLng(39.943962, 3.891220),
title: 'Title',
content: '<div><h1>Lorem ipsum</h1>Lorem ipsum dolor sit amet<div>'
});
openMarker(0);