js:
var map;
function initialize() {
$('#refreshmap').on('click',initialize);
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(-29.3456, 151.4346),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
var marker = new google.maps.Marker({
position: pos,
title: 'Position',
map: map,
draggable: true,
visible:true
});
updateMarkerPosition(pos);
geocodePosition(pos);
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerPosition(marker.getPosition());
});
$('#button').click(function(){
marker.setVisible(true);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html:
<div id="map-canvas"></div>
<button type="button" id="button" class="map_buttons button_style">Add marker</button>
The above code is for display marker on current location by clicking a button.Map is showing the current location but marker is not working.
I am getting this error in console "Uncaught ReferenceError: pos is not defined".
Try this:
var map;
var pos;
function initialize() {
$('#refreshmap').on('click', initialize);
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Try HTML5 geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
}, function () {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(-29.3456, 151.4346),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
var marker = new google.maps.Marker({
position: pos,
title: 'Position',
map: map,
draggable: true,
visible: true
});
updateMarkerPosition(pos);
geocodePosition(pos);
google.maps.event.addListener(marker, 'drag', function () {
updateMarkerPosition(marker.getPosition());
});
$('#button').click(function () {
marker.setVisible(true);
});
}
Basically, declare var pos in the global scope, and remove var while initializing pos
The issue is that
During creation of the marker object, pos is undefined in the scope
try to declare pos global, like your map
var map;
var pos;
Related
I have this simple script on a web page, loading a small kml file, but when I add geolocation, it always centers the map on the current location.
And I want to load the map centered on the kml file. User location should only be displayed if he is in the area of the kml, or if he drags the map to the area where he is located.
Accessorily, is there a way to easily refresh the user location on the map with javascript (maps api 3), without re-centering the map ?
var map;
function initialize() {
var centre = new google.maps.LatLng(4,4);
var mapOptions = {
zoom: 11,
center: centre
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var ctaLayer = new google.maps.KmlLayer({
url: 'http://www.server.com/kmlfile.kml',
preserveViewport: false
});
ctaLayer.setMap(map);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
// map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
So, here is my latest update, I added the disableAutoPan: true option to infoWindow, as indicated, and to refresh the user position I used watchPosition in place of getCurrentPosition, together with setPosition to move theinfoWindow position :
var map;
function initialize() {
var center_map = new google.maps.LatLng(45,-4);
var mapOptions = {
zoom: 11,
center: centre
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var ctaLayer = new google.maps.KmlLayer({
url: 'http://www.server.com/kmlfile.kml', preserveViewport: false
});
var ctaLayer.setMap(map);
if(navigator.geolocation) {
navigator.geolocation.watchPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
if(typeof infowindow == "undefined") {
infowindow = new google.maps.InfoWindow({
disableAutoPan: true,
map: map, position: pos,
content: 'Your position',
zIndex: 0 /* not needed */
});
}
else {
infowindow.setPosition(pos);
}
}, function() {
/*handleNoGeolocation(true);*/
/* had to delete this because errors centered the map on North Pole */
},
{ timeout: 10000, enableHighAccuracy: true }); /* high accuracy for tests */
}
};
google.maps.event.addDomListener(window, 'load', initialize);
Apparently it works although I suppose it's quite raw...
When you open the InfoWindow it is panning the map to display it. Set disableAutoPan to true in the InfoWindowOptions.
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.',
disableAutoPan: true
});
proof of concept fiddle
code snippet:
var map;
function initialize() {
var centre = new google.maps.LatLng(4, 4);
var mapOptions = {
zoom: 11,
center: centre
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var ctaLayer = new google.maps.KmlLayer({
url: 'http://www.geocodezip.com/geoxml3_test/cta.xml',
preserveViewport: false
});
ctaLayer.setMap(map);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
disableAutoPan: true,
map: map,
position: pos,
content: 'Location found using HTML5.'
});
// map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content,
disableAutoPan: true
};
var infowindow = new google.maps.InfoWindow(options);
// map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>
I am trying to have places come up on the map based on the users geolocation. I know the geolocation works and map shows up, but none of the markers come up showing the local businesses. I am not getting any errors in console as well. I made sure that the script in my html is passing both the library and the API key, but just in case, here is the script:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&key=MY_KEY"></script>
Here is my JavaScript...
var map;
var infowindow;
var service;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
mapTypeControl: false,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
scaleControl: true,
streetViewControl: false
});
// Start Geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Found You!'
});
var request = {
location: pos,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
// Callback for Places
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
// Create Marker for Places
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);
});
}
// Google Maps Error Flags
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
Here is my updated coded that I got to work.. I made some customizations to the markers, but this works now. As mentioned in the comments, I believe the issue had to do with the variables set for infowindow. I changed the geolocation one to 'infowindowLocation' instead and adjusted in the error flags section.
var map;
var infowindow;
var service;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
mapTypeControl: false,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
scaleControl: true,
streetViewControl: false
});
// Start Geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindowLocation = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Found You!'
});
var request = {
location: pos,
radius: 3218.69,
types: ['dentist']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
// Callback for Places
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
// Create Marker for Places
function createMarker(place) {
var placeLoc = place.geometry.location;
var image = 'img/flag.png';
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
title: place.name,
animation: google.maps.Animation.DROP,
icon: image
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map,marker);
});
}
// Google Maps Error Flags
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindowLocation = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
initialize();
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;
What i am trying to do is find my current location with the Geolocation API, and then add the google places, to show what is around myself. However what I have so far only returns a specific location...
<script>
var map;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, 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);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
As you can see pyrmont - gives me the lat and long, but i would like to replace with this the users current location. So I can find out where they are and then give them some shops. I keep drawing a blank when I try to do this. I have done geolocation before with:
new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
however if I use this var in the lat long section I get a loverly error. Thanks for any help in advance.
Okay this did it:
<script>
var map;
function initialize() {
var mapOptions = {
};
map = new google.maps.Map(document.getElementById('contact-map'),{
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var request = {
location: pos,
radius: 500,
types: ['store']
};
var marker = new google.maps.MarkerImage('../img/layout/marker.png');
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
icon: marker,
content: 'youre here'
});
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, 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);
});
}
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Right now I have google map code that will set a single marker on a map. What I want is for that single marker to be moved to whatever coordinates the user clicks on. I only want 1 marker on the map, so I need that single marker to be moved to whatever location is clicked. Any help is appreciated. Thanks!
var initialLocation;
var siberia = new google.maps.LatLng(60, 105);
var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var browserSupportFlag = new Boolean();
function initialize() {
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
myListener = google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
google.maps.event.removeListener(myListener);
});
google.maps.event.addListener(map, 'drag', function(event) {
placeMarker(event.latLng);
google.maps.event.removeListener(myListener);
});
// Try W3C Geolocation (Preferred)
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
// Try Google Gears Geolocation
} else if (google.gears) {
browserSupportFlag = true;
var geo = google.gears.factory.create('beta.geolocation');
geo.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeoLocation(browserSupportFlag);
});
// Browser doesn't support Geolocation
} else {
browserSupportFlag = false;
handleNoGeolocation(browserSupportFlag);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag === true) {
alert("Geolocation service failed.");
initialLocation = newyork;
} else {
alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
initialLocation = siberia;
}
}
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
draggable: true
});
map.setCenter(location);
var markerPosition = marker.getPosition();
populateInputs(markerPosition);
google.maps.event.addListener(marker, "drag", function (mEvent) {
populateInputs(mEvent.latLng);
});
}
function populateInputs(pos) {
document.getElementById("t1").value=pos.lat()
document.getElementById("t2").value=pos.lng();
}
}
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#map_canvas {height:600px;width:800px}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var markersArray = [];
function initMap()
{
var latlng = new google.maps.LatLng(41, 29);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// add a click event handler to the map object
google.maps.event.addListener(map, "click", function(event)
{
// place a marker
placeMarker(event.latLng);
// display the lat/lng in your form's lat/lng fields
document.getElementById("latFld").value = event.latLng.lat();
document.getElementById("lngFld").value = event.latLng.lng();
});
}
function placeMarker(location) {
// first remove all markers if there are any
deleteOverlays();
var marker = new google.maps.Marker({
position: location,
map: map
});
// add marker in markers array
markersArray.push(marker);
//map.setCenter(location);
}
// Deletes all markers in the array by removing references to them
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
</head>
<body onload="initMap()">
<div id="map_canvas"></div>
<input type="text" id="latFld">
<input type="text" id="lngFld">
</body>
</html>
The current answers do a lot more work than is necessary by removing and re-adding the marker(s). The best way to do this is to use the setPosition() function that the Google Maps API provides for this purpose.
Here is your code modified to use setPosition() to move the pointer:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#map_canvas { height:600px; width:800px }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var initialLocation;
var siberia = new google.maps.LatLng(60, 105);
var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var browserSupportFlag = new Boolean();
function initialize() {
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker;
myListener = google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
google.maps.event.addListener(map, 'drag', function(event) {
placeMarker(event.latLng);
});
// Try W3C Geolocation (Preferred)
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
// Try Google Gears Geolocation
} else if (google.gears) {
browserSupportFlag = true;
var geo = google.gears.factory.create('beta.geolocation');
geo.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeoLocation(browserSupportFlag);
});
// Browser doesn't support Geolocation
} else {
browserSupportFlag = false;
handleNoGeolocation(browserSupportFlag);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag === true) {
alert("Geolocation service failed.");
initialLocation = newyork;
} else {
alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
initialLocation = siberia;
}
}
function placeMarker(location) {
if (marker) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map,
draggable: true
});
google.maps.event.addListener(marker, "drag", function (mEvent) {
populateInputs(mEvent.latLng);
});
}
populateInputs(location);
}
function populateInputs(pos) {
document.getElementById("t1").value=pos.lat()
document.getElementById("t2").value=pos.lng();
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
<input type="text" id="t1">
<input type="text" id="t2">
</body>
</html>
You can try:
google.maps.event.addListener(map, 'click', function(event){
var marker_position = event.latLng;
marker = new google.maps.Marker({
map: map,
draggable: false
});
marker.setPosition(marker_position);
})
Make a global javascript variable "marker".
Then in your listener add the if marker exists statement and remove it if true
myListener = google.maps.event.addListener(map, 'click', function(event) {
if(marker){marker.setMap(null)}
placeMarker(event.latLng);
google.maps.event.removeListener(myListener);
});
try this
if (marker) { marker.setMap(null) }
marker = new google.maps.Marker({ position: event.latLng, map: map });
Burak Erdem answer works fine, but actually you dont need and array to do that, it is enough one var since it is only one last marker, becouse when you set a new one, you delete inmediatly the last one. I did it with this few lines and it worked fine:
var map;
var lastMarker;
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: new google.maps.LatLng(-25.363882, 131.044922),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(map_canvas, map_options)
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
if (lastMarker != null)
lastMarker.setMap(null);
var marker = new google.maps.Marker({
position: location,
map: map
});
lastMarker = marker;
}
google.maps.event.addDomListener(window, 'load', initialize);
I accomplished this with the following:
// create a new marker
var marker = new google.maps.Marker({
});
//add listener to set the marker to the position on the map
google.maps.event.addListener(map, 'click', function(event) {
marker.setPosition(event.latLng);
marker.setMap(map);
marker.setAnimation(google.maps.Animation.DROP);
});
It creates a marker and then move it to each mouse click location...
I also added a drop marker animation as well.
Instead of creating multiple markers this creates one marker and moves it to the clicked location.