Google Maps api v3 - map with a single marker only - javascript

I'm creating a map in Google Maps that I want to have only one marker. When the user clicks on the map for the first time, a marker would be created (with a circle around it). When the user clicks again, the old marker (and circle) is shifted to the new location.
So basically, this would be done by either moving the marker and circle, or by deleting them and creating a new marker and circle.
At the moment I'm trying to use the latter method, but unfortunately it's not working. Could anyone help?
<script>
//Initial variables (map and the markers array, which we're going to try to get rid of)
var map;
var markersArray = [];
//and GO!
function initialize()
{
//need to correct our starting location - over UK would be nice
var haightAshbury = new google.maps.LatLng(37.7699298, -122.4469157);
var mapOptions =
{
zoom: 12,
center: haightAshbury,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
//listen out for clicks and, when clicked, add a marker
google.maps.event.addListener(map, 'click', function(event)
{
addMarker(event.latLng);
});
}
// Add a marker to the map and push to the array.
function addMarker(location)
{
markersArray = [];
setAllMap(null);
var marker = new google.maps.Marker(
{
position: location,
map: map,
draggable: true
});
//create a circle
var circle = new google.maps.Circle(
{
map: map,
radius: 3000
});
//bind the circle to the marker we've also just created
circle.bindTo('center', marker, 'position');
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

If you only want one marker at a time you do not need an array to store markers. You have to make sure you clear the map property of the marker and the circle using the setMap method and passing null. The circle is wrong, you do not have all the options you need and there is no bindTo method. Here is the circle documentation.
I saw that you set the marker's draggable propery to true so you also need to add a dragend event on the marker to relocate the circle to the markers new position using the setCenter method on the circle.
here is a complete example:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Google Maps</title>
<style>
#map_canvas{
height:800px;
width:800px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script>
var marker, myCircle, map;
function initialize() {
var myLatlng = new google.maps.LatLng(37.7699298, -122.4469157);
var mapOptions = {
zoom: 12,
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){
addMarker(event.latLng);
});
}
function addMarker(latLng){
//clear the previous marker and circle.
if(marker != null){
marker.setMap(null);
myCircle.setMap(null);
}
marker = new google.maps.Marker({
position: latLng,
map: map,
draggable:true
});
//circle options.
var circleOptions = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: latLng,
radius: 3000
};
//create circle
myCircle = new google.maps.Circle(circleOptions);
//when marker has completed the drag event
//recenter the circle on the marker.
google.maps.event.addListener(marker, 'dragend', function(){
myCircle.setCenter(this.position);
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>

Related

google maps marker stop

this is my google maps code
ı want to google maps marker stop
help me please !!!
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// initialize marker
var marker = new google.maps.Marker({
position: map.getCenter(),
draggable: true,
map: map
});
//marker.forEach(function (marker) {
// marker.setMap(null);
//});
//marker = [];
// intercept map and marker movements
window.google.maps.event.addListener(map, "idle", function() {
marker.setPosition(map.getCenter());
var latitude = map.getCenter().lat().toFixed(6);
var longitude = map.getCenter().lng().toFixed(6);
window.google.maps.event.trigger(map, "resize");
getLocationAdressName(latitude, longitude);
marker.dragging.disable();
});
As dev8080 answered, if you want your marker to be not draggable at all then you should go with his answer.
But if you want your marker stop being draggable after some event replace
this:
marker.dragging.disable();
with this:
marker.setDraggable(false);
Initialize the pointer with draggable:false. To set the marker's center, you need not enable it's draggable attribute.
var marker = new google.maps.Marker({
position: map.getCenter(),
draggable: false,
map: map
});

Marker is not showing up on google map

I am trying to show markers on google map in a web page.
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
window.MY = {};
function test() {
addMarker(new google.maps.LatLng(88.4, 22.5));
}
function addMarker(myLatlng) {
var marker = new google.maps.Marker({
position: myLatlng,
map: MY.map
});
}
function initialize() {
var myOptions = {
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
MY.map = new google.maps.Map(document.getElementById("googleMap"), myOptions);
navigator.geolocation.getCurrentPosition(function(position) {
MY.map.setCenter(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
});
google.maps.event.addListener(MY.map, 'click', function(event) {
addMarker(event.latLng);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="height:380px;"></div>
<button onclick="test()">test</button>
</body>
</html>
When I click on the map, marker shows up, but when I click on test button, marker doesn't show up for the specified location(88.4, 22.5). Can someone please explain me the behavior.
The location google.maps.LatLng(88.4,22.5) is above the arctic circle. A latitude of 88.4 is very close to the north pole.
Perhaps you want google.maps.LatLng(22.5,-88.4) (in the Gulf of Mexico) or google.maps.LatLng(22.5,88.4) (Kolkata, India).
Replace your function test with
function test() {
var position = new google.maps.LatLng(88.4, 22.5)
addMarker(position);
MY.map.setCenter(position);
}
Your marker is falling outside map's viewport.

Google Map API marker update from JS

I would like to ask you a solution for this problem.
I have a JS with a variable inside that is updated overtime by a JAVA application (i.e. JAVA writer into a thread), after that I take the coordinates from that variable and I create a new object Marker for my google maps. The problem is that the marker does not changes position, it changes only if I refresh the whole page (I dont want to do this).
Here's the code to be more clear.
The inputData.js where the variable is written by the java application
var newMarker = {'latitude':38.25705300000004,'longitude': 140.83760400000006};
my html page used to display the map
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MYKEY">
</script>
<script type="text/javascript" src="inputData.js"></script>
<script>
var map;
var sendai = new google.maps.LatLng(38.259535, 140.846816);
var lastPosition;
var image = 'images/circle-16.png';
function initialize() {
var mapOptions = {
zoom: 12,
center: sendai,
mapTypeId: google.maps.MapTypeId.ROADMAP};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
setInterval(refreshData, 2000);
function refreshData() {
var marker = new google.maps.Marker({
map: map,
icon: image,
draggable: false
});
marker.setPosition(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setCenter(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setZoom(18);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
If I open my page like this everything work but when I change the script "inputData.js" the marker does not changes position.
The method setCenter on the other hand seems to work properly.
Help me please!
You'll need to reload the updated script to get the updated position:
function initialize() {
var mapOptions = {
zoom: 18,
center: sendai,
mapTypeId: google.maps.MapTypeId.ROADMAP},
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions),
//we will store the LatLng here
pos = new google.maps.MVCObject(),
//use a single marker with updated position
marker = new google.maps.Marker();
//set the latLng of the MVCObject
pos.set('latLng',new google.maps.LatLng(newMarker.latitude,
newMarker.longitude));
//bind the markers position to the latLng of the MVCObject
marker.bindTo('position',pos,'latLng');
marker.setMap(map);
setInterval(function(){
//the currently loaded script
var script=document.querySelector('script[src^="inputData.js"]'),
//the updated script
update=document.createElement('script');
//load-handler for the updated script
google.maps.event.addDomListenerOnce(update,'load',function(){
pos.set('latLng',new google.maps.LatLng(newMarker.latitude,
newMarker.longitude));
map.setCenter(pos.get('latLng'));
map.setZoom(18);
});
//replace current script with updated script
script.parentNode.replaceChild(update,script);
//load update
update.src='inputData.js?'+new Date().getTime();
},2000);
}
You don't need to create new instance of marker every time. Update your code with this and try:
var map;
var sendai = new google.maps.LatLng(38.259535, 140.846816);
var lastPosition;
var image = 'images/circle-16.png';
function initialize() {
var mapOptions = {
zoom: 12,
center: sendai,
mapTypeId: google.maps.MapTypeId.ROADMAP};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
var marker;
marker = new google.maps.Marker({
map: map,
icon: image,
draggable: false
});
marker.setPosition(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setCenter(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setZoom(18);
setInterval(refreshData, 2000);
function refreshData() {
marker.setPosition(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setCenter(new google.maps.LatLng(newMarker.latitude, newMarker.longitude));
map.setZoom(18);
}
google.maps.event.addDomListener(window, 'load', initialize);

google maps marker is not defined

This is my code
var map_canvas = document.getElementById('map_canvas');
var map_options = { center: new google.maps.LatLng(44.5403, -78.5463), zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP }
map = new google.maps.Map(map_canvas, map_options);
google.maps.event.addListener(map, 'click', function(event) {
if(marker){
marker.setMap(null);
}
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
$("#latitude").val(event.latLng.lat());
$("#longitude").val(event.latLng.lng());
map.setCenter(event.latlng);
});
console.log($("#longitude").val());
if (($("#latitude").val()) && ($("#longitude").val())){
var point = new google.maps.LatLng(($("#latitude").val()), ($("#longitude").val()));
marker = new google.maps.marker({
position: point,
map: map
});
map.setCenter(point, 8);
}
please notice that I have added a listener for on click on the map to add the marker, and it is working. I mean when I click on the map, the marker appears.
However, when I submit the page, and if there is an error in the inputs, I return the page back to the user. In that case, if the use has added a map, I wanted to create the map for him. that is why I used this code:
console.log($("#longitude").val());
if (($("#latitude").val()) && ($("#longitude").val())){
var point = new google.maps.LatLng(($("#latitude").val()), ($("#longitude").val()));
marker = new google.maps.marker({
position: point,
map: map
});
map.setCenter(point, 8);
however, i got exception Uncaught TypeError: undefined is not a function in the line marker = new google.maps.marker({ could you help please?
Make sure you use the right capitalization for Google Maps API function names, google.maps.marker should be google.maps.Marker.

How do I change the mouse cursor when I mouseover on a particular area in Google Map v3?

Using the Google Maps API v3: How do I change the mouse cursor when I mouseover on a particular area?
Yes, this is possible by setting draggableCursor in MapOptions, as in the following example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps v3 Change Cursor Demo</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 350px"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById("map"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 8,
center: new google.maps.LatLng(-34.3, 150.6)
});
var ne = new google.maps.LatLng(-34.00, 150.00);
var nw = new google.maps.LatLng(-34.00, 150.50);
var sw = new google.maps.LatLng(-35.00, 150.50);
var se = new google.maps.LatLng(-35.00, 150.00);
var boundingBox = new google.maps.Polyline({
path: [ne, nw, sw, se, ne],
strokeColor: '#FF0000'
});
boundingBox.setMap(map);
google.maps.event.addListener(map, 'mousemove', function(event) {
if ((event.latLng.lat() > se.lat()) && (event.latLng.lat() < ne.lat()) &&
(event.latLng.lng() > ne.lng()) && (event.latLng.lng() < sw.lng())) {
map.setOptions({ draggableCursor: 'crosshair' });
}
else {
map.setOptions({ draggableCursor: 'url(http://maps.google.com/mapfiles/openhand.cur), move' });
}
});
</script>
</body>
</html>
If you run the above example, the cursor would change to a cross hair once the mouse is moved inside the red rectangle.
Other answers advising to to put 'mousemove' listeners on the whole map object will work but are wrong. This is 'heavy handed' and a bad idea as listeners like these can add up in a real application and when combined with other things happening on your map, can cause serious performance problems and possibly unforeseen race conditions!
The BEST way to do this is to use the google.maps.Polygon class. This allows you to pass a series of LatLng objects to create a Polygon. This polygon is rendered on the map and has a default mouseover attribute of 'pointer', you can add a 'mouseover' listener to the object returned from the new google.maps.Polygon class call.
The source below is from this example
http://code.google.com/apis/maps/documentation/javascript/examples/polygon-simple.html
var myLatLng = new google.maps.LatLng(24.886436490787712, -70.2685546875);
var myOptions = {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var bermudaTriangle;
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var triangleCoords = [
new google.maps.LatLng(25.774252, -80.190262),
new google.maps.LatLng(18.466465, -66.118292),
new google.maps.LatLng(32.321384, -64.75737)
];
bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: "#FF0000",
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
Then I can add the listener like this
google.maps.event.addListener(bermudaTriangle, 'mouseover', function() {
map.setZoom(8);
});
//now if you mouse over the Polygon area, your map will zoom to 8

Categories

Resources