I am trying to develop a page which has a button that can be pressed. When pressed it should execute some functions, but before execution it should first be validated by location. So whenever a user is in a default set location (region like polygon) the button can be pressed without returning an error. And when not in that location or some other error it should give a warning/error.
What plugin/library/code is best to use for this? Any tips how?
Thank you!
If you are using html5 you can use navigator.geolocation.getCurrentPosition to get location.
Reference: https://www.w3schools.com/html/html5_geolocation.asp
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
Once you got location you can use [Google Maps Geometry Library], for Polygon specifically you can use:
Reference: https://developers.google.com/maps/documentation/javascript/examples/poly-containsLocation
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Polygon arrays</title>
<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>
// This example requires the Geometry library. Include the libraries=geometry
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry">
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 24.886, lng: -70.269},
zoom: 5,
});
var triangleCoords = [
{lat: 25.774, lng: -80.19},
{lat: 18.466, lng: -66.118},
{lat: 32.321, lng: -64.757}
];
var bermudaTriangle = new google.maps.Polygon({paths: triangleCoords});
google.maps.event.addListener(map, 'click', function(e) {
var resultColor =
google.maps.geometry.poly.containsLocation(e.latLng, bermudaTriangle) ?
'blue' :
'red';
var resultPath =
google.maps.geometry.poly.containsLocation(e.latLng, bermudaTriangle) ?
// A triangle.
"m 0 -1 l 1 2 -2 0 z" :
google.maps.SymbolPath.CIRCLE;
new google.maps.Marker({
position: e.latLng,
map: map,
icon: {
path: resultPath,
fillColor: resultColor,
fillOpacity: .2,
strokeColor: 'white',
strokeWeight: .5,
scale: 10
}
});
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry&callback=initMap"
async defer></script>
</body>
</html>
Related
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.
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
In the following code I've added a custom control on a map using Google Maps API V3.
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<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>
var map;
function initMap() {
var myOptions = {
zoom: 8,
center: {lat: -34.397, lng: 150.644},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
//### Add a button on Google Maps ...
var controlMarkerUI = document.createElement('DIV');
controlMarkerUI.style.cursor = 'pointer';
controlMarkerUI.style.backgroundColor = 'blue';
controlMarkerUI.style.height = '28px';
controlMarkerUI.style.width = '25px';
controlMarkerUI.style.top = '11px';
controlMarkerUI.style.left = '120px';
controlMarkerUI.title = 'Click to get the coordinates';
map.controls[google.maps.ControlPosition.LEFT_TOP].push(controlMarkerUI);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=<PUT_YOUR_KEY_HERE>&callback=initMap"
async defer></script>
</body>
</html>
Now I'd like to associate a function at the custom control tha simply return the click coordinates when a user click on the map.
I can do it (without associate the function to the customcontrol ... ), in this manner
google.maps.event.addListener(map, 'click', function (e) {
alert("Latitude: " + e.latLng.lat() + "\r\nLongitude: " + e.latLng.lng());
});
but I'd like to activate / deactivate this function clicking on my custom control.
Suggestions / examples?
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<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: 70%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<button id="start">Start</button>
<button id="clearClick">Clear</button>
<script>
var map;
var listener1;
function initMap() {
var myOptions = {
zoom: 8,
center: {lat: -34.397, lng: 150.644},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
//### Add a button on Google Maps ...
var controlMarkerUI = document.createElement('DIV');
controlMarkerUI.style.cursor = 'pointer';
controlMarkerUI.style.backgroundColor = 'blue';
controlMarkerUI.style.height = '28px';
controlMarkerUI.style.width = '25px';
controlMarkerUI.style.top = '11px';
controlMarkerUI.style.left = '120px';
controlMarkerUI.title = 'Click to get the coordinates';
listener1= google.maps.event.addListener(map, 'click', function
(e) {
alert("Latitude: " + e.latLng.lat() + "\r\nLongitude: " + e.latLng.lng());
});
document.getElementById("clearClick").onclick = function(){
google.maps.event.removeListener(listener1);
}
document.getElementById("start").onclick = function(){
listener1= google.maps.event.addListener(map, 'click', function
(e) {
alert("Latitude: " + e.latLng.lat() + "\r\nLongitude: " + e.latLng.lng());
});
}
map.controls[google.maps.ControlPosition.LEFT_TOP].push(controlMarkerUI);
}
</script>
<script>
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap"
async defer></script>
</body>
</html>
For further ref below link
https://developers.google.com/maps/documentation/javascript/events
Merging #Murali answer and this answer https://gis.stackexchange.com/questions/244132/how-to-associate-function-to-custom-controls-in-google-maps-api/244141#244141, I solved in this way ....
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<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>
var map;
var listenerHandle;
//Enable-Disable the functionality
function show_XY(e){
listenerHandle = google.maps.event.addListener(map, 'click', alert_XY);
}
function alert_XY(e){
alert("Latitude: " + e.latLng.lat() + "\r\nLongitude: " + e.latLng.lng());
}
function removeListener(e){
google.maps.event.removeListener(listenerHandle);
}
function initMap() {
var myOptions = {
zoom: 8,
center: {lat: -34.397, lng: 150.644},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
//### Add a button on Google Maps ...
var controlEditUI = document.createElement('DIV');
controlEditUI.id = "controlEditUI";
controlEditUI.style.cursor = 'pointer';
controlMarkerUI.style.backgroundColor = 'blue';
controlEditUI.style.height = '28px';
controlEditUI.style.width = '25px';
controlEditUI.style.top = '11px';
controlEditUI.style.left = '120px';
controlEditUI.title = 'Click to get the coordinates';
map.controls[google.maps.ControlPosition.LEFT_TOP].push(controlEditUI);
controlEditUI.addEventListener('click', show_XY);
//### Add a button on Google Maps ...
var controlTrashUI = document.createElement('DIV');
controlTrashUI.id = 'controlTrashUI';
controlTrashUI.style.cursor = 'pointer';
controlMarkerUI.style.backgroundColor = 'black';
controlTrashUI.style.height = '28px';
controlTrashUI.style.width = '25px';
controlTrashUI.style.top = '11px';
controlTrashUI.style.left = '150px';
controlTrashUI.title = 'Click to set the map to Home';
map.controls[google.maps.ControlPosition.LEFT_TOP].push(controlTrashUI);
controlTrashUI.addEventListener('click', removeListener);
};
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=<PUT_YOUR_KEY_HERE>&callback=initMap"
async defer></script>
</body>
</html>
I'm working in location tracking module using AngularJS and JavaScript. My objective is to set the position of individual user according to receiving latitude and longitude as well as moving of marker.On below code I'm getting markers but not moving. Please suggest
var marker = new google.maps.Marker({
position: pos,
map: $scope.map
});
for (var k = 0; k < $scope.arr.length; k++) {
var found = $scope.arr.some(function (el) {
return el.from === name;
});
if (!found) {
$scope.arr.push({
from: name,
marker: marker,
latitude: $scope.LocInfor.latitude,
longitude: $scope.LocInfor.longitude
});
}
var pos = new google.maps.LatLng($scope.arr[k].latitude, $scope.arr[k].longitude);
marker.setPosition(pos);
}
In javascript, the navigator.geolocation.watchPosition() method is used to register a handler function that will be called automatically each time the position of the device changes. You can also, optionally, specify an error handling callback function.
Syntax:
navigator.geolocation.watchPosition(success[, error[, options]])
success
A callback function that takes a Position object as an input parameter.
error (optional)
An optional callback function that takes a PositionError object as an input parameter.
options (optional)
An optional PositionOptions object.
And, now, for your problem, you can use this code. Be care full, you should replace YOUR-API-KEY by your google's 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>
<div id="map"></div>
<script>
var map;
var marker = new google.maps.Marker({
position: pos,
map: map,
title: "Test"
});
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
getLocationUpdate ();
}
function showLocation(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
marker.setPosition(pos);
map.setCenter(pos);
alert("Latitude : " + pos.lat + " Longitude: " + pos.lng);
}
function errorHandler(err) {
if(err.code == 1) {
alert("Error: Access is denied!");
}
else if( err.code == 2) {
alert("Error: Position is unavailable!");
}
}
function getLocationUpdate(){
if(navigator.geolocation){
// timeout at 60000 milliseconds (60 seconds)
var options = {
enableHighAccuracy: false,
timeout: 5000,
maximumAge: 0
};
var geoLoc = navigator.geolocation;
geoLoc.watchPosition(showLocation, errorHandler, options);
}
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY&callback=initMap">
</script>
I'm sure this is a basic problem but I've hit my head against the wall too many times now, so hopefully someone will take pity on me!
I have the following example but all it does is show a grayed out box, no map at all. Can anyone tell me why?
I've checked that I'm actually returning a result and it seems to be working fine.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html, body, #map-canvas {margin: 0;padding: 0;height: 100%;}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize()
{
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': "England"}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(results[0].geometry.location),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// Let's draw the map
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
initialize();
</script>
</head>
<body onload="">
<div id="map-canvas" style="width: 320px; height: 480px;"></div>
</body>
</html>
Try resizing the browser window, give a shake to browser/drag it from browser tab with the cursor and you will see the map appearing.
From some strange reason in MVC partial view google map comes as blank, your map is working it just need to be resized.
Shaking a browser window with cursor sounds funny, but it works and I am not sure how to best describe it.
Thanks,
Anurag
=======================================================================
my final working code is below:
`
<script type="text/javascript">
$(document).ready(function () {
(function () {
var options = {
zoom: 6,
center: new google.maps.LatLng(-2.633333, 37.233334),
mapTypeId: google.maps.MapTypeId.TERRAIN,
mapTypeControl: false
};
// init map
var map = new google.maps.Map(document.getElementById('map_canvas'), options);
var arrLocation = [];
$("#markerDiv").find("div").each(function () {
var Lat = $(this).find("input[id='Latitude']").val();
var Lon = $(this).find("input[id='Longitude']").val();
var Id = $(this).find("input[id='Id']").val();
var AssessmentDet = $(this).find("input[id='AssessmentDateTime']").val();
var LocAcc = $(this).find("input[id='LocationAccuracy']").val();
var assessorName = $(this).find("input[id='AssessorName']").val();
var partnerName = $(this).find("input[id='PartnerName']").val();
arrLocation.push({
Id: Id,
Latitude: Lat,
Longitude: Lon,
AssessmentDate: AssessmentDet,
LocationAccuracy: LocAcc,
AssessorDetail: assessorName,
PartnerName: partnerName
});
});
var allMarkers = [];
for (var i = 0; i < arrLocation.length; i++) {
//final position for marker, could be updated if another marker already exists in same position
var latlng = new google.maps.LatLng(arrLocation[i].Latitude, arrLocation[i].Longitude);
var finalLatLng = latlng;
var comparelatlng = "(" + arrLocation[i].Latitude + "," + arrLocation[i].Longitude + ")";
var copyMarker = arrLocation[i];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(arrLocation[i].Latitude, arrLocation[i].Longitude),
map: map,
title: 'Equine # ' + arrLocation[i].Id,
icon:"abc.png"
});
var markerInfo = "Reference # : <b>" + arrLocation[i].Id + "</b><br/>";
markerInfo = markerInfo + "Assessor : <b>" + arrLocation[i].AssessorDetail + "</b><br/>";
markerInfo = markerInfo + "Date : <b>" + arrLocation[i].AssessmentDate + "</b><br/>";
markerInfo = markerInfo + "Partner : <b>" + arrLocation[i].PartnerName + "</b>";(function (marker, i) {
bindInfoWindow(marker, map, new google.maps.InfoWindow(), markerInfo);
})(marker, i);
}
})();
});
function bindInfoWindow(marker, map, infowindow, html) {
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(html);
infowindow.open(map, marker);
});
}
</script>
`
results[0].geometry.location is already a latLng object so you can just say:
center: results[0].geometry.location
Find the working fiddle here : http://jsfiddle.net/87z9K/
It is because of the worng "google.maps.LatLng" provided.
provide for a test the coords and it will work.
replace the line
center: new google.maps.LatLng(results[0].geometry.location),
with
center: new google.maps.LatLng(-34.397, 150.644)
get England coords
It wasn't exactly your issue, but closely related.
I found that I had to set the mapOptions with a valid centre, like so:
new google.maps.Map(mapCanvas, {
center: new google.maps.LatLng(-34.397, 150.644)
});
If I didn't enter map options, or if I did and it didn't have a valid center set, I'd get a blank map that didn't load tiles.
This can also occur if the height/width of the map is 0.
I tried to set map's MapTypeId and it helped as Anurag proposed:
map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
I can see a general javascript issue with your code.
Your script might trying to embed the map in the page before the HTML is loaded.
Call the function like this (there are other ways).
<body onload="initialize()">