Geolocation: moving only google maps marker without reload the map - javascript

I need to update only the marker when the device is moving or when the device is getting more accuracy. When the position change also reload the map and I need to move only the maker. I have the following code:
if (navigator.geolocation) {
navigator.geolocation.watchPosition(
function(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;
var coords = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: 20,
center: coords,
streetViewControl: false,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var capa = document.getElementById("capa");
capa.innerHTML = "latitud: " + latitude + " longitud: " + " aquesta es la precisio en metres : " + accuracy;
map = new google.maps.Map(
document.getElementById("mapContainer"), mapOptions
);
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "ok"
});
},function error(msg){alert('Please enable your GPS position future.');
}, {maximumAge:0, timeout:5000, enableHighAccuracy: false});
}else {
alert("Geolocation API is not supported in your browser.");
}
Thanks!

I believe that the problem is that you create a new map inside the watchPosition function. You only need to create one marker and then update its position inside the watchPosition function.
navigator.geolocation.watchPosition(
function (position) {
setMarkerPosition(
currentPositionMarker,
position
);
});
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
}
Maybe this example will help you:
<!doctype html>
<html lang="en">
<head>
<title>Google maps</title>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"></script>
<script type="text/javascript">
var map,
currentPositionMarker,
mapCenter = new google.maps.LatLng(40.700683, -73.925972),
map;
function initializeMap()
{
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 13,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function locError(error) {
// the current position could not be located
alert("The current position could not be found!");
}
function setCurrentPosition(pos) {
currentPositionMarker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
),
title: "Current Position"
});
map.panTo(new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
));
}
function displayAndWatch(position) {
// set current position
setCurrentPosition(position);
// watch position
watchCurrentPosition();
}
function watchCurrentPosition() {
var positionTimer = navigator.geolocation.watchPosition(
function (position) {
setMarkerPosition(
currentPositionMarker,
position
);
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
}
function initLocationProcedure() {
initializeMap();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
} else {
alert("Your browser does not support the Geolocation API");
}
}
$(document).ready(function() {
initLocationProcedure();
});
</script>
</head>
<body>
<div id="map_canvas" style="height:600px;"></div>
</body>
</html>

one easy way to do is, simply call map.clearOverlays(); then read add new positions with map.addOverlay(<marker>)

Related

setCenter doesn't seem to accept any objects i feed into it

I have been working on this for hours, but I can't seem to find the correct object feed into setCenter for this particular scenario:
var map,
currentPositionMarker,
mapCenter = new google.maps.LatLng(14.668626, 121.24295)
function initializeMap(){
map = new google.maps.Map(_('map'), {
zoom: 18,
center: mapCenter,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
}
function locError(error) { alert("current position not be found");}
function setCurrentPosition(pos) {
currentPositionMarker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
),
title: "Current Position"
});
map.panTo(new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
));
}
function displayAndWatch(position) {
setCurrentPosition(position);
watchCurrentPosition(position);
}
function watchCurrentPosition(pos) {
var positionTimer = navigator.geolocation.watchPosition(
function (position) {
setMarkerPosition(
currentPositionMarker,
position
);
**map.setCenter(google.maps.LatLng(pos.coords.latitude,pos.coords.latitude));**
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
}
function initLocationProcedure() {
initializeMap();
infoWindow = new google.maps.InfoWindow({ maxWidth: 400 });
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
} else { alert("Geolocation API not supported"); }
}
(it's especially frustrating as I have to drive around the block to verify if each change works!).
Anyone know what I am doing wrong in the map.setCenter line above?
you have to set it like this:
map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));

I can't change the size of the radius using input box and button for the user Google Map API

I have the following code and I want to set and change the circle's radius through user's input using input box and button. Any help will be appreciated. EDIT. This is the revised code based on the example provided below but still won't work for me. Every help will be appreciated.
<apex:page controller="GeoLocatorController" sidebar="false" showheader="false">
<head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { width:100%;height:80%; }
.controls
</style>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBJkHXEVXBSLY7ExRcxoDxXzRYLJHg7qfI"></script>
<script>
var circle;
function initialize() {
//Setting default center of the system
var mapCenter = {
center: new google.maps.LatLng(36.2048, 138.2529),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"), mapCenter);
//Get User's Geolocation and Set as the Center of the System
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
userLat = position.coords.latitude;
userLng = position.coords.longitude;
userLoc = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(userLoc);
//User Marker's Image
var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
//Create Marker for the User's Location
var centerLoc = new google.maps.Marker({
position : new google.maps.LatLng(userLat, userLng),
map : map,
icon: image,
title : 'Your Position!',
draggable : true,
animation: google.maps.Animation.DROP
});
//Create Circle and Bind it to User's Location
circle = new google.maps.Circle({
map: map,
radius: 100, // 10 miles in metres
fillColor: '#AA0000'
});
circle.bindTo('center', centerLoc, 'position');
marker.setMap(map);
});
function updateRadius(){
var rad = document.getElementById("value_rad").value;
circle.setRadius(parseFloat(rad));
}
}
loadHotels();
}
//Load Records from Cloud
function loadHotels({Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.GeoLocatorController.findAll}',
function(result, event){
if (event.status) {
for (var i=0; i<result.length; i++) {
var id = result[i].Id;
var name = result[i].Name;
var lat = result[i].Location__Latitude__s;
var lng = result[i].Location__Longitude__s;
addMarker(id, name, lat, lng);
}
} else {
alert(event.message);
}
},
{escape: true}
);
}
//Create Markers for the Records from the Cloud
function addMarker(id, name, lat, lng) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
title: name,
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
console.log()
</script>
</head>
<body>
<div id="googleMap" style="width:100%;height:80%;"/>
<input id="value_rad" />
<input id="radius" type="button" value="Search" onclick="updateRadius()"/>
</body>
</apex:page>
See this code (it's work), and adapt your code
var user_lat;
var user_lng;
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
user_lat = crd.latitude;
user_lng = crd.longitude;
};
function error(err) {
alert('ERROR(' + err.code + '): ' + err.message);
};
var circle;
var myCenter;
function initialize() {
navigator.geolocation.getCurrentPosition(success, error, options);
myCenter = new google.maps.LatLng(user_lat, user_lng);
var mapProp = {
center: myCenter,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var marker = new google.maps.Marker({
position: myCenter,
});
circle = new google.maps.Circle({
map: map,
radius: 100, // 10 miles in metres
fillColor: '#AA0000',
center: myCenter
});
marker.setMap(map);
}
function updateRadius(){
var rad = document.getElementById("value_rad").value;
circle.setRadius(parseFloat(rad));
}
google.maps.event.addDomListener(window, 'load', initialize);
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBJkHXEVXBSLY7ExRcxoDxXzRYLJHg7qfI"></script>
<div id="googleMap" style="width:500px;height:380px;"></div>
<input id=value_rad />
<input id="radius" type="button" value="test" onclick="updateRadius()"/>

Geolocation Change Marker Position

I use geolocation and I can view map my coordinates. Then, marker put the coordinate.
I want to change marker position.
My code here:
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition,showError);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
lat=position.coords.latitude;
lon=position.coords.longitude;
latlon=new google.maps.LatLng(lat, lon)
mapholder=document.getElementById('mapholder')
mapholder.style.height='250px';
mapholder.style.width='100%';
var myOptions={
center:latlon,zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP,
mapTypeControl:false,
navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}
};
var map=new google.maps.Map(document.getElementById("mapholder"),myOptions);
var marker=new google.maps.Marker({position:latlon,map:map,title:"You are here!"});
This code get my location coordinates. How can i change marker position?
I am sorry Eren about the my previous answer.I misunderstood.I think , this is correct one what you needed.
Display latitude and longitude on marker movement
Refer this site
I found a solution in this page. My problem is solved with this.
refer this
and this site
var map;
var myCenter = new google.maps.LatLng(37, 35);
var markersArray = [];
function clearOverlays() {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
function initialize() {
var mapProp = {
center: myCenter,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
google.maps.event.addListener(map, 'click', function (event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
clearOverlays();
var marker = new google.maps.Marker({
position: location,
map: map,
});
markersArray.push(marker);
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() + '<br>Longitude: ' + location.lng()
});
infowindow.open(map, marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
moveBus() is getting called before initialize(). Try putting that line at the end of your initialize() function. Also Lat/Lon 0,0 is off the map (it's coordinates, not pixels), so you can't see it when it moves. Try 54,54. If you want the center of the map to move to the new location, use panTo().
Demo: http: //jsfiddle.net/ThinkingStiff/Rsp22/
HTML:
<script src = "http://maps.googleapis.com/maps/api/js?sensor=false" > </script> <div id = "map-canvas"> </div>
CSS:
#map-canvas {
height: 400 px;
width: 500 px;
}
Script:
function initialize() {
var myLatLng = new google.maps.LatLng(50, 50),
myOptions = {
zoom: 4,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
marker = new google.maps.Marker({
position: myLatLng,
map: map
});
marker.setMap(map);
moveBus(map, marker);
}
function moveBus(map, marker) {
marker.setPosition(new google.maps.LatLng(0, 0));
map.panTo(new google.maps.LatLng(0, 0));
};
initialize();

Geolocation google maps jquery

I'm trying to do a script that locates the current position of the user and after reload of the page sets out a random coordinate. I can initilize the map and the random coordinate functions but the geolocation doesn't seem to locate my position, allthough it prints out the message in the infowindow?
var map;
var pos;
function initialize() {
//here is the starting for the map, where it will begin to show
var latlng = new google.maps.LatLng(59.2982762, 17.9970823);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
//geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: "You are here"
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
}
else {
handleNoGeolocation(false);
}
function handleNoGeolocation(errorflag) {
if (errorflag) {
alert('Geolocation not supported');
initialLocation = stockholm;
}
else {
alert('balblababa');
initialLocation = siberia;
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options, position);
}
//stop geolocation
var flagAreas = [
[59.2967322, 18.0009393],
[59.2980245, 17.9971503],
[59.2981078, 17.9980875],
[59.2982762, 17.9970823],
[59.2987638, 17.9917639],
[59.2987649, 17.9917824],
[59.2987847, 17.9917731],
[59.2988498, 17.991684],
[59.2988503, 17.9981593],
[59.3008233, 18.0041763],
[59.3014033, 18.0068793],
[59.3016619, 18.0137766]
];
var random = flagAreas.sort(function() {
return Math.random() - 0.5 })[0];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(random[0], random[1]),
map: map,
});
}
window.onload = initialize;
</script>
Thanks to Suvi Vignarajah.
Here is the working code!
var map;
var pos;
function initialize() {
//here is the starting for the map, where it will begin to show
var latlng = new google.maps.LatLng(59.2982762, 17.9970823);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
//geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: initialLocation,
content: "You are here"
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
}
else {
handleNoGeolocation(false);
}
function handleNoGeolocation(errorflag) {
if (errorflag) {
alert('Geolocation not supported');
initialLocation = stockholm;
}
else {
alert('balblababa');
initialLocation = siberia;
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options, position);
}
//stop geolocation
var flagAreas = [
[59.2967322, 18.0009393],
[59.2980245, 17.9971503],
[59.2981078, 17.9980875],
[59.2982762, 17.9970823],
[59.2987638, 17.9917639],
[59.2987649, 17.9917824],
[59.2987847, 17.9917731],
[59.2988498, 17.991684],
[59.2988503, 17.9981593],
[59.3008233, 18.0041763],
[59.3014033, 18.0068793],
[59.3016619, 18.0137766]
];
var random = flagAreas.sort(function() {
return Math.random() - 0.5 })[0];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(random[0], random[1]),
map: map,
});
}
window.onload = initialize;

google maps and geolocation with markers javascript

i want to make a google maps that shows the current location of the user and it should also be possible that the user can click on the map to add markers. i can do them separately but it fails when i try to combine them.
this is my code for the geolocation
function success(position) {
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcontainer';
mapcanvas.style.height = '500px';
mapcanvas.style.width = '600px';
document.querySelector('article').appendChild(mapcanvas);
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var options = {
zoom: 15,
center: coords,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapcontainer"), options);
var marker = new google.maps.Marker({
position: coords,
map: map,
title:"You are here!"
});
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
error('Geo Location is not supported');
}
and this is my code to add markers to the map.
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
map.setCenter(location);
}
check out the folllowing link..the example in it will help you surely.worked for me too.
http://www.codeproject.com/Articles/291499/Google-Maps-API-V3-for-ASP-NET

Categories

Resources