Remove a circle object from a Google Map - google-maps

I have checked multiple similar posts on SO but haven't yet found the answer. I have a Google map app that when you Zoom in the marker changes from an icon to a circle. It works great. The Marker icon is replaced by the circle object. But, I also want it to work in reverse: As you zoom out, I want to remove the circle and replace it with the icon. I can get the icon to "reappear" but I can't figure out a way to get a reference to the circle object that is bound to the Marker so I can remove it.
This is NOT the complete code that I am using but to satisfy the request for something MINIMAL rather than complete, this would create the issue:
var marker;
createamarker();
removeCircle();
function createamarker(){
marker = new google.maps.Marker({
position: location,
map: map,
icon: icon,
// Add some custom properties
obscure:obscure,
originalpin: icon
});
// Add circle overlay and bind to marker
var circle = new google.maps.Circle({
map: map,
radius: 1000, // in metres
fillColor: '#AA0000'
});
// Bind it to the marker
circle.bindTo('center', marker, 'position');
}
I also have a second function that is SUPPOSED to remove the circle:
function removeCircle(){
// remove whatever is there
marker.setMap(null);
var icon = {
url: marker.originalpin,
scaledSize: new google.maps.Size(22,32)
}
// reset the marker icon
marker.icon = icon;
//sets the marker back
marker.setMap(map);
// NOW REMOVE the circle:
// So at this point I am stuck. I have bound a circle to
// the marker but in order to REMOVE the circle I need a
// reference to it. Other SO postings suggest acting on the
// circle object directly like so:
circle.setMap(null);
// but the "circle" doesn't exist here. It was bound to the marker in another function. I need a reference to the circle that was bound to the marker so I can act on it.
}

To do what you are looking to do, one option would be to set the circle as a property of the marker:
marker.circle = circle;
Then you can hide the circle like this:
marker.circle.setMap(null);
Note that this won't work if the circle is global, it needs to be local to the createamarker function.
proof of concept fiddle
code snippet:
var map;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = createamarker(map.getCenter());
removeCircle(marker);
var marker2 = createamarker(new google.maps.LatLng(37.45, -122.14));
google.maps.event.addDomListener(document.getElementById('toggle'), 'click', function() {
marker.circle.setMap(marker.circle.getMap() == null ? map : null);
marker2.circle.setMap(marker2.circle.getMap() == null ? map : null);
});
}
google.maps.event.addDomListener(window, "load", initialize);
function createamarker(location) {
var icon = "http://maps.google.com/mapfiles/ms/micons/blue.png";
marker = new google.maps.Marker({
position: location,
map: map,
icon: icon,
// Add some custom properties
// obscure: obscure,
originalpin: icon
});
// Add circle overlay and bind to marker
var circle = new google.maps.Circle({
map: map,
radius: 1000, // in metres
fillColor: '#AA0000'
});
// Bind it to the marker
circle.bindTo('center', marker, 'position');
marker.circle = circle;
return marker;
}
function removeCircle(marker) {
// remove whatever is there
marker.setMap(null);
var icon = {
url: marker.originalpin,
scaledSize: new google.maps.Size(22, 32)
}
// reset the marker icon
marker.icon = icon;
//sets the marker back
marker.setMap(map);
// NOW REMOVE the circle:
// So at this point I am stuck. I have bound a circle to
// the marker but in order to REMOVE the circle I need a
// reference to it. Other SO postings suggest acting on the
// circle object directly like so:
marker.circle.setMap(null);
// but the "circle" doesn't exist here. It was bound to the marker in another function. I need a reference to the circle that was bound to the marker so I can act on it.
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input type="button" value="toggle circle" id="toggle" />
<div id="map_canvas"></div>

Related

create a polyline with multiple points, then join an added marker to a line segment google maps v3

I have a google map that I am plotting a route on and linking my points with a polyline. I create a new point on the line with a right click on the map. I also have the ability to create a point of interest along my path and I'm using a different marker icon for those as well as showing an info window with the POI text.
google.maps.event.addListener(Map, "rightclick", function (event) {
var markerIndex = polyLine.getPath().length;
polyLine.setMap(Map);
var isFirstMarker = markerIndex === 0;
var marker;
var poiText = "";
if(!isAddingPOI) {
marker = new google.maps.Marker({
map: Map,
position: event.latLng,
draggable: true,
icon: '/images/waypoint.png'
});
} else {
poiText = prompt("Enter a short description for this point of interest", "");
if (poiText != null) {
marker = new google.maps.Marker({
map: Map,
position: event.latLng,
draggable: true,
icon: '/images/point_of_interest.png',
info: new google.maps.InfoWindow({
content:poiText
})
});
}
}
if (isAddingPOI) {
predefinedPositions.push(new predefinedPosition(event.latLng.lat(), event.latLng.lng(), poiText));
google.maps.event.addListener(marker, 'click', function () {
marker.info.open(Map, marker);
});
isAddingPOI = false;
} else {
predefinedPositions.push(new predefinedPosition(event.latLng.lat(), event.latLng.lng()));
}
polyLine.getPath().push(event.latLng);
outlineMarkers.push(marker);
google.maps.event.addListener(marker, 'drag', function (dragEvent) {
polyLine.getPath().setAt(markerIndex, dragEvent.latLng);
predefinedPositions[markerIndex].Latitude = dragEvent.latLng.lat();
predefinedPositions[markerIndex].Longitude = dragEvent.latLng.lng();
updateDistance(outlineMarkers);
});
updateDistance(outlineMarkers);
});
what I need now is the ability for the user to specify a LatLng for a new marker which would be placed on the map as draggable and then to be able to merge (by dragging) that marker to my created path. Ideally, I'd like for the segment of the polyline where the marker is dragged to change colors while the marker is over it. I'll then need to add that marker to the path array for the final output.
I found this which is the closest to what I want that I could find but it's not quite what I'm looking for: Google Maps API v3 - Draggable Marker Along a Polyline
I also tried adding a 'mouseover' event to my polyline to update the color which doesn't ever get triggered while I'm dragging a marker. It also updates the entire polyline's color (not just the segment) when I mouse over it. I'm sure I can sort out the segment color change myself, but I'm stuck on dragging the marker over the line and having it change colors and ultimately merging it to my path.
any suggestions would be greatly appreciated.
TIA
I got it sorted out using something similar to this: Confine dragging of Google Maps V3 Marker to Polyline
I didn't get the polyline segment to change colors, but this "snap-to" functionality is really close to what I was looking for.
try this way
//data sample
var cities = [
{
city : 'Mayestik Tailor',
desc : 'Jln Aspal Rata',
lat : -6.2426373,
lng : 106.7907953
},
{
city : 'Bubur Ayam Barito',
desc : 'Jl. Gandaria Tengah 3, Kramat Pela, Kebayoran Baru',
lat : -6.2457674,
lng : 106.790865
},
{
city : 'Apartment Permata Gandaria',
desc : 'Jl. Kyai Moh. Syafii Hadzami/Jl. Taman Gandaria',
lat : -6.2450461,
lng : 106.7882604
}
];
create function to center point of layout
var mapOptions = {
zoom: 15,
center:new google.maps.LatLng(-6.2451528,106.7901808),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var createMarker = function (info){
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(info.lat, info.lng),
title: info.city
});
}
var arr = [];
for (i = 0; i < cities.length; i++){
arr.push(new google.maps.LatLng(cities[i].lat, cities[i].lng));
}
// create polyline
var flightPath = new google.maps.Polyline({
path: arr,
geodesic: true,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
// loop for marker
for (i = 0; i < cities.length; i++){
createMarker(cities[i]);
}
for css class
#map {
height:420px;
width:600px;
}
.infoWindowContent {
font-size: 14px !important;
border-top: 1px solid #ccc;
padding-top: 10px;
}
h2 {
margin-bottom:0;
margin-top: 0;
}
on HTML Code
<div id="map"></div>

google map, show tooltip on a circle

I know I can make a marker with a tooltip that shows "SOMETHING" like this:
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lon),
map: map,
draggable: true,
title:"SOMETHING",
icon: '/public/markers-map/male-2.png'
});
I want to do the same with a circle but title doesn't work.
new google.maps.Circle({
center: new google.maps.LatLng(lat,lon),
radius: 20,
strokeColor: "blue",
strokeOpacity: 1,
title:"SOMETHING",
strokeWeight: 1,
fillColor: "blue",
fillOpacity: 1,
map: map
});
It prints the circle but does not show the message "SOMETHING".
How can I do it? is there another property to get it?
Thanks in advance.
The tooltip is created via the native title-attribute of DOM-elements, but the API doesn't provide any method to access the DOMElement that contains the circle.
A possible workaround may be to use the title-attribute of the map-div instead(set it onmouseover and remove it onmouseout)
//circle is the google.maps.Circle-instance
google.maps.event.addListener(circle,'mouseover',function(){
this.getMap().getDiv().setAttribute('title',this.get('title'));});
google.maps.event.addListener(circle,'mouseout',function(){
this.getMap().getDiv().removeAttribute('title');});
You can also use InfoWindow instead of html title attribute, as the title may not show up always on mouse over. InfoWindow looks pretty good.
var infowindow = new google.maps.InfoWindow({});
var marker = new google.maps.Marker({
map: map
});
Then use same mouseover event mechanism to show the InfoWindow:
google.maps.event.addListener(circle, 'mouseover', function () {
if (typeof this.title !== "undefined") {
marker.setPosition(this.getCenter()); // get circle's center
infowindow.setContent("<b>" + this.title + "</b>"); // set content
infowindow.open(map, marker); // open at marker's location
marker.setVisible(false); // hide the marker
}
});
google.maps.event.addListener(circle, 'mouseout', function () {
infowindow.close();
});
Also we can add event listener direct on google.maps.Circle instance.
Code sample:
//circle is the google.maps.Circle-instance
circle.addListener('mouseover',function(){
this.getMap().getDiv().setAttribute('title',this.get('title'));
});
circle.addListener('mouseout',function(){
this.getMap().getDiv().removeAttribute('title');
});
Just wrote for alternative!

multiple mouse events not triggering

I am using google maps api. I want to have two mouse events ready to trigger at one time. Below is a code snipit.
function initialize() {
var myLatlng = new google.maps.LatLng(37.4419, -122.1419);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var polyOptions = {
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3 }
poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
// Add a listener for the click event
google.maps.event.addListener(map, 'click', addLatLng);
}
function addLatLng(event) {
var path = poly.getPath();
if(!draw)
{
path.push(event.latLng);
path.push(event.latLng);
draw = true;
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map });
google.maps.event.addListener(map, 'mousemove', moveTrackLine);
}
else
{
path.push(event.latLng);
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map });
draw = false;
}
}
function moveTrackLine(event) {
var path = poly.getPath();
// replace the old point with a new one to update the track
path.pop();
path.push(event.latLng);
}
When I click on the map the first time I see a marker placed on the map. Then when the mouse is moved I see the polyline update and follow my curser correctly. Next if I click on the map I do not see a marker placed on the map nor do I ever go into the addLatLng function. Thanks in advance for your help and time.
-tim
set the clickable-option of the polyline to false.
The issue: As soon as the mousemove-event is applied to the map, you will not be able to click on the map anymore, because below the mouse-cursor is always the polyline.
When you set the clickable-option of the polyline to false, the polyline does not respond to mouse-events and the click-event will be passed to the map.

change the place of the marker with the click

i am working on google maps, what i want to do is to click on the map it add a marker to the map its working fine but the problem is that i need to move the same marker to a new place if i click some where else instead of new marker. and also when i click on any point it give me the address of that place in a text field
here is my code
<script type="text/javascript">
var map;
var markersArray = [];
function initialize() {
var haightAshbury = new google.maps.LatLng(37.7699298, -122.4469157);
var mapOptions = {
zoom: 7,
center: haightAshbury,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListenerOnce(map, 'click', function(event) {
addMarker(event.latLng);
});
}
function addMarker(location) {
marker = new google.maps.Marker({
position: location,
map: map
});
markersArray.push(marker);
}
// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
}
}
You can call clearOverlays anytime you create a new marker.this way you hide the previous marker and only the new is shown.
another way is to have a var marker just as you have a var map. you can edit the markers position in addMarker.
as far as geocoding is concerned take a look at this

Get a parameter from a binded element in Google Maps

Previously I get an answer to the linking of an element. My next question is: how can I get the "radius" parameter of a binded circle, from the marker?
The code:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
});
var circle = new google.maps.Circle({
map: map,
radius: 50,
});
circle.bindTo('map', marker);
circle.bindTo('center', marker, 'position');
Array.push(marker);
I need the cirlce's radius, which binded to the Array[x] marker. Any idea? Thanks in advance!
I don't think there's a way to get a bound object from an object.
What you can do is set the circle as an object on the marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
});
var circle = new google.maps.Circle({
map: map,
radius: 50,
});
marker.circle = circle; // Add the circle object to the map object
circle.bindTo('map', marker);
circle.bindTo('center', marker, 'position');
Array.push(marker);
Now you can get the radius with
Array[x].circle.getRadius();
Working example