How can I move marker position as the user moves? - javascript

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>

Related

Move marker continuously as per user location

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.

Validate user by location JAVASCRIPT

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>

Google Places API sorting by radius or distance

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

Google Maps Api Nearby Search - Why does google.maps.places.RankBy.DISTANCE return fewer results?

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.

Multiple Locations Google map

How can i show multiple locations on google map.
I am using this code for google map?
<script type="text/javascript">
$(function() { // when the document is ready to be manipulated.
if (GBrowserIsCompatible()) { // if the browser is compatible with Google Map's
var map = document.getElementById("myMap"); // Get div element
var m = new GMap2(map); // new instance of the GMap2 class and pass in our div location.
var longArray= ("<?php echo $long; ?>").split(',');
var latArray= ("<?php echo $lat; ?>").split(',');
for(i=0;i<longArray.length;i++)
{
m.setCenter(new GLatLng(latArray[i], longArray[i]), 13); // pass in latitude, longitude, and zoom level.
m.openInfoWindow(m.getCenter(), document.createTextNode("This is testing")); // displays the text
}
m.setMapType(G_SATELLITE_MAP); // sets the default mode. G_NORMAL_MAP, G_HYBRID_MAP
var c = new GMapTypeControl(); // switch map modes
m.addControl(c);
m.addControl(new GLargeMapControl()); // creates the zoom feature
}
else {
alert("Upgrade your browser, man!");
}
});
</script>
Refer below code, that worked perfectly fine for me.
The code snippet below will give you an error to provide valid API key i.e. "Google Maps JavaScript API error: InvalidKeyMapError", to resolve this the only thing you need is valid API Key provided by google maps.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Multiple Locations using Google Maps </title>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=false"></script>
</head>
<body>
<div id="googleMap" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
var locationArray = [
['Pune', 18.5248904, 73.7228789, 1],
['Mumbai', 19.0825223, 72.7410977, 2],
['Ahmednagar', 19.1104918, 74.6728675, 3],
['Surat', 21.1594627, 77.3507354, 4],
['Indore', 22.7242284, 75.7237617, 5]
];
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 8,
center: new google.maps.LatLng(18.5248904,73.7228789),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locationArray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locationArray[i][1], locationArray[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locationArray[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
</body>
</html>
For more details refer here. I hope this is what you are looking for!
setCenter is used to zoom and center the map.. if you want to mark multiple locations you need to create a marker and place it on the map inside your loop.. there's a good set of tutorials here:
http://econym.org.uk/gmap/index.htm
If your question relates to showing multiople disparate locations on a single map then you cant, a map can only be centered on one lat/lng at a time..
Its not entirely clear what you're trying to achieve.
Dunc.
following steps you have to follow.
1. make a list of your addresses in javascript aaray.
2. make a utility function to geocode and then put marker by passing address as arguement.
3. iterate over your addresses array and call your marker utility function.
example: map.jsp ::
it tales input json string that is list of addresses and the converts it to javascript array:
add the jquery and infobox.js by downloading fron google.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# page contentType="text/html;charset=windows-1252"%>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script language="JavaScript" src="js/jquery-1.8.0.min.js" type="text/javascript"></script>
<script language="JavaScript" src="js/infobox.js" type="text/javascript"></script>
</head>
<body>
<%
String json=request.getParameter("address");
%>
<input type="hidden" id="json" value="<%=json%>"></input>
<div id="map" style="width: 1250px; height: 500px;" align="center"></div>
<script type="text/javascript" language="JavaScript" src="js/map.js"></script>
<script type="text/javascript">
var jsonvalue=document.getElementById("json").value;
var use=unescape(jsonvalue);
//alert(use);
var obj = eval ("(" + use + ")");
var cobj=obj.center;
var olist=obj.other;
codeproject(cobj.center_add,cobj.center_name);
//alert(cobj.center_name+" and "+cobj.center_add);
for(var i=0;i<olist.length;i++)
{
//alert(olist[i].other_add);
codeAddress(olist[i].other_add,olist[i].other_name);
}
</script>
</body>
</html>
________map.js________
//used by infowindow
//the googlemap code
var geocoder = new google.maps.Geocoder();
//var infowindow = new google.maps.InfoWindow();
var LatLngList = new Array(6);
var i;
var infowindow = new google.maps.InfoWindow();
var markerBounds = new google.maps.LatLngBounds();
var markerarray=new Array();
//making the div for window popup
var boxText = document.createElement("div");
boxText.style.cssText = "border: 2px solid Gray; margin-top: 6px; background: white; padding: 5px;font-weight: bold;color: Gray;";
boxText.innerHTML = " ";
//options array for infobox window
var myOptions = {
map:map,
content : boxText,
disableAutoPan : false,
maxWidth : 0,
pixelOffset : new google.maps.Size( - 140, 0),
zIndex : null,
boxStyle : { background : "url('tipbox.gif') no-repeat", width : "280px" },
closeBoxMargin : "10px 4px 2px 2px", closeBoxURL : "close.gif",
infoBoxClearance : new google.maps.Size(1, 1),
isHidden : false,
pane : "floatPane",
enableEventPropagation : true
};
var infoBox;
function codeproject(address, client) {
geocoder.geocode( {
'address' : address
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker( {
map : map, icon : 'green-dot.png', position : results [0].geometry.location, draggable : false, animation : google.maps.Animation.DROP
});
//bounce the marker
// marker.setAnimation(google.maps.Animation.BOUNCE);
//initialize info box
infoBox = new InfoBox(myOptions);
markerBounds.extend(results[0].geometry.location);
//listeners
google.maps.event.addListener(marker, 'mouseover', function () {
//stop bouncing
// marker.setAnimation(null);
// $("img[src$='iws3.png']").hide();
// infowindow.setContent('<b>' + client + '<\/b><br>'+ results[0].formatted_address);
// infowindow.open(map, this);
boxText.innerHTML = "<br>"+client +"<br>"+results[0].formatted_address;
infoBox.setContent(boxText,marker);
infoBox.open(map,marker);
});
google.maps.event.addListener(marker, 'mouseout', function () {
// infowindow.close();
infoBox.close();
//start bounce
// marker.setAnimation(google.maps.Animation.BOUNCE);
});
//ok end
}
else {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
alert("Error Occured during geocode:" + status);
}
// alert('Geocode was not successful for '+client +' the following reason: ' + status);
}
});
}
function codeAddress(address, client) {
// var address = document.getElementById('address').value;
geocoder.geocode( {
'address' : address
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// map.setCenter(results[0].geometry.location);
infoBox = new InfoBox(myOptions);
var marker = new google.maps.Marker( {
map : map,
// icon : 'smallpin.png',
position : results[0].geometry.location, draggable : false, animation : google.maps.Animation.DROP
});
//make bounds
//bounce the marker
// marker.setAnimation(google.maps.Animation.BOUNCE);
//initialize info box
markerBounds.extend(results[0].geometry.location);
//listeners
google.maps.event.addListener(marker, 'mouseover', function () {
//stop bouncing
// marker.setAnimation(null);
$("img[src$='iws3.png']").hide();
// infowindow.setContent('<b>' + client + '<\/b><br>'+ results[0].formatted_address + '<\br>');
//infowindow.open(map, this);
boxText.innerHTML = "<br>"+client +"<br>"+results[0].formatted_address ;
infoBox.setContent(boxText,marker);
infoBox.open(map,marker);
});
google.maps.event.addListener(marker, 'mouseout', function () {
// infowindow.close();
//start bounce
infoBox.close();
// marker.setAnimation(google.maps.Animation.BOUNCE);
});
//ok end
}
else {
// alert('Geocode was not successful for '+client +' the following reason: ' + status);
}
});
}
//////////////calling the above two functions
var centerpoint = new google.maps.LatLng(43.652527, - 79.381961);//for ontario canada zoom level-7
//map intializing
var map = new google.maps.Map(document.getElementById('map'),
{
zoom : 4, backgroundColor : '#B5B5B5', draggable : true, center : centerpoint, mapTypeId : google.maps.MapTypeId.ROADMAP
});
///geocoding multiple addresses
//bounce markers
function toggleBounce(mark) {
if (mark.getAnimation() != null) {
mark.setAnimation(null);
}
else {
mark.setAnimation(google.maps.Animation.BOUNCE);
}
}
/////
function putmarker(address,client,lat,lng) {
var position = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker( {
map : map, icon : 'green-dot.png', position : position, draggable : false, animation : google.maps.Animation.DROP
});
//bounce the marker
// marker.setAnimation(google.maps.Animation.BOUNCE);
//initialize info box
infoBox = new InfoBox(myOptions);
markerBounds.extend(position);
//listeners
google.maps.event.addListener(marker, 'mouseover', function () {
//stop bouncing
// marker.setAnimation(null);
// $("img[src$='iws3.png']").hide();
// infowindow.setContent('<b>' + client + '<\/b><br>'+ results[0].formatted_address);
// infowindow.open(map, this);
boxText.innerHTML = "<br>"+client +"<br>"+address;
infoBox.setContent(boxText,marker);
infoBox.open(map,marker);
});
google.maps.event.addListener(marker, 'mouseout', function () {
// infowindow.close();
infoBox.close();
//start bounce
// marker.setAnimation(google.maps.Animation.BOUNCE);
});
//ok end
}

Categories

Resources