I could not delete polygon when marker is click - google-maps-api-3

I am trying to delete a polygon when my marker is being clicked,but i could not get how to make this work that the polygon will be deleted.I appreciate someone will help me to make this work.
This my demo in jsfiddle.
Demo
here is my code it's not working.
var map;
var count = 0;
var polycolor = '#ED1B24';
var polyarray = [];
var marker;
var markers = [];
var path = new google.maps.MVCArray;
function initialize() {
var initial = new google.maps.LatLng(53.199246241276875, -105.76864242553711);
var mapOptions = {
zoom: 16,
center: initial,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
mapTypeControl: false
};
poly.setPaths(new google.maps.MVCArray([path]));
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
google.maps.event.addListener(map, 'click', function (e) {
addMarker(e);
addPolygon(e);
});
}
var deletepolygon = function (pt) {
i = 0;
var thepath = poly.getPath();
thepath.forEach(function (ltlng) {
i++;
if ((ltlng.lat() + "," + ltlng.lng()) == pt) {
path.removeAt(i);
}
});
}

Related

Google Maps InfoBubble windows neither closing nor recentering map

I have a successful working GM prototype using InfoBubble here.
I need the map to recenter when I open each new InfoBubble window.
The map recenters on closing each InfoBubble because I call [line 238 etc]:
google.maps.event.addListener(infoBubble, "closeclick", function ()
Secondly, why doesn't the Los Angeles (United States West Coast, LA) InfoBubble also close the most recent InfoBubble window open as all the others do, please?
Thanks so much in advance for any suggestions; I know it must be simple - but have spent hours and hours and searched S/O too!
javascript:
$(document).ready(function () { initialize(); });
var myLatlng = new google.maps.LatLng(51.30, 0.7);
function initialize() {
google.maps.Map.prototype.setCenterWithOffset = function(LatLng, offsetX, offsetY) {
var map = this;
var ov = new google.maps.OverlayView();
ov.onAdd = function() {
var proj = this.getProjection();
var aPoint = proj.fromLatLngToContainerPixel(LatLng);
aPoint.x = aPoint.x+offsetX;
aPoint.y = aPoint.y+offsetY;
map.setCenter(proj.fromContainerPixelToLatLng(aPoint));
};
ov.draw = function() {};
ov.setMap(this);
};
var centerMap = new google.maps.LatLng(51.30, 0.7);
var mapOptions = {
zoom: 2,
disableDefaultUI: true,
scrollwheel: false,
navigationControl: false,
mapTypeControl: false,
scaleControl: false,
draggable: false,
center: centerMap,
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setCenterWithOffset(myLatlng, 50, 225);
setMarkers(map, sites);
google.maps.event.addListener(infoBubble, "closeclick", function () {
map.setCenterWithOffset(myLatlng, 50, 225);
});
google.maps.event.addListener(infoBubbleLA, "closeclick", function () {
map.setCenterWithOffset(myLatlng, 50, 225);
});
};
var infoBubble = new InfoBubble({
maxWidth: 400,
});
var infoBubbleLA = new InfoBubble({
maxWidth: 400,
});
// locationstrings start
var losangeles1 = 'losangeles1';
var losangeles2 = 'losangeles2';
var losangeles3 = 'losangeles3';
var losangeles4 = 'losangeles4';
var losangelescontentString ='losangelescontentString';
var portonovocontentstring ='Porto Novo';
var shackletoncontentstring = 'Shackleton';
var florencecontentstring = 'Florence';
var buenosairescontentstring = 'Buenos Aires';
var jodhpurcontentstring = 'Jodhpur';
var mtsinaicontentstring = 'Mt Sainai';
var neworleanscontentstring = 'New Orleans';
var pariscontentstring='Paris';
// locationstrings end
infoBubbleLA.addTab('Electronic Cataloguing Initiative', losangeles1);
infoBubbleLA.addTab('Getty Leadership Institute at Claremont Graduate University', losangeles2);
infoBubbleLA.addTab('Tab 3', losangeles3);
infoBubbleLA.addTab('Preserve L.A.', losangeles4);
var sites = [
// 'Title', lat, long, contentstring
['Los Angeles', 34.054082,-118.24261, losangelescontentString],
['Porto Novo', 6.501411,2.604275, portonovocontentstring],
['Shackleton', -77.550000, 166.150000, shackletoncontentstring],
['Florence', 43.773046,11.255901, florencecontentstring],
['Buenos Aires', -34.578528,-58.526273, buenosairescontentstring],
['Jodhpur', 27.199507,73.73826, jodhpurcontentstring],
['Mt Sinai', 28.555972,33.975048, mtsinaicontentstring],
['New Orleans', 29.984676,-90.063171, neworleanscontentstring],
['Paris', 48.821799,2.404933, pariscontentstring]
];
var iconBase = 'http://gettylabs.org/visit/FoundationMap/images/';
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var sites = markers[i];
var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
var marker = new google.maps.Marker({
icon: iconBase + 'bullet.png',
title: sites[0],
position: siteLatLng,
html: sites[3],
map: map
});
google.maps.event.addListener(marker, "click", function () {
map.setCenterWithOffset(myLatlng, 50, 25);
if (this.html == losangelescontentString) {
infoBubbleLA.setContent(this.html);
infoBubbleLA.open(map,this);
} else {
infoBubble.setContent(this.html);
infoBubble.open(map,this);
}
});
};
};
You have 2 different InfoBubbles in you code infoBubbleLA and infoBubble. Opening one won't close the the other.
var infoBubble = new InfoBubble({
maxWidth: 400,
});
var infoBubbleLA = new InfoBubble({
maxWidth: 400,
});
This should do that:
google.maps.event.addListener(marker, "click", function () {
map.setCenterWithOffset(myLatlng, 50, 25);
if (this.html == losangelescontentString) {
infoBubbleLA.setContent(this.html);
infoBubbleLA.open(map,this);
infoBubble.close();
} else {
infoBubble.setContent(this.html);
infoBubble.open(map,this);
infoBubbleLA.close();
}
});
working fiddle

Google maps v3 geocode multiple custom markers by address or latlng

I need to plot multiple custom map markers using MapsV3 api either by an address or lat/lon. I put together the following code which works ok for lon/lat, but if the data contains an address the geocoder returns nothing. Any ideas on how to fix this.
$(document).ready(function () { initialize(); });
function initialize() {
var centerMap = new google.maps.LatLng(-27.0,133.0);
var options = {
panControl: false,
zoomControl: true,
scaleControl: false,
mapTypeControl: false,
streetViewControl: false,
zoom: 3,
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), options);
var data = [
{
'title':'F C Building Construction ...',
'address':'',
'zindex':20,
'lat':'-33.797847',
'lon':'151.259928',
'marker_number':1,
'marker_html':' html content...',
'image': {
url:'//localhost/assets/images/markers/marker_1.png',
size: new google.maps.Size(24, 29),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(10, 29)
}
}];
setMarkers(map, data);
var infowindow = new google.maps.InfoWindow();
}
function showMapPin(i) { }
function setMarkers(map,data) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < data.length; i++) {
setMarker(map, data[i], bounds);
}
map.fitBounds(bounds);
}
function setMarker(map, m, bounds) {
if(m["address"]!="") {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { "address": m["address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var siteLatLng = results[0].geometry.location;
}
});
} else {
var siteLatLng = new google.maps.LatLng(m["lat"], m["lon"]);
}
if(siteLatLng) {
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
//shadow: shadow,
icon: m["image"],
title: m["title"],
zIndex: m["zindex"],
html: m["marker_html"]
});
bounds.extend(siteLatLng);
google.maps.event.addListener(marker, "click", function() {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
} // if latlng
}//]]>
After looking back over the code I realized that the variable siteLatLng is within geocode function scope so it never gets passed and it can't be returned. Setting the marker within this function works.

Google Map Marker not being replaced

please excuse a noob at this. When a user clicks on a map, it should place a marker and open an info window - as per this example: http://www.geocodezip.com/v3_example_click2add_infowindow.html
The code below almost works correctly, except that the mark is not replaced - a new one is added. Any ideas really, really gratefully received. Thank you.
<script>
var map = null;
var markersArray = [];
function initialize() {
var latlng = new google.maps.LatLng(0.0000, 0.0000);
var settings = {
zoom: 2,
mapTypeControl:true,
center: latlng,
panControl:true,
zoomControl:true,
streetViewControl:false,
overviewMapControl:false,
rotateControl:true,
scaleControl: true,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.DEFAULT
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
backgroundColor: 'white'
};
map = new google.maps.Map(document.getElementById('map'), settings);
function placeMarker(location) {
var marker , i ;
if ( marker ) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
icon:'http://www.desperatesailors.com/templates/Live/media/mapicons/info.png',
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() +
'<br>Longitude: ' + location.lng() +
'<br>Only the first four decimal places needed'
});
infowindow.open(map,marker);
}
}
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
window.onload = initialize;
</script>
This is a scope issue. You are always delcaring marker in the placeMarker function so if( marker ) will always be false. Move the variable declaration out of that function:
<script>
var marker;
var map = null;
var markersArray = [];
function initialize() {
var latlng = new google.maps.LatLng(0.0000, 0.0000);
var settings = {
zoom: 2,
mapTypeControl:true,
center: latlng,
panControl:true,
zoomControl:true,
streetViewControl:false,
overviewMapControl:false,
rotateControl:true,
scaleControl: true,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.DEFAULT
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
backgroundColor: 'white'
};
map = new google.maps.Map(document.getElementById('map'), settings);
function placeMarker(location) {
var i ;
if ( marker ) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
icon:'http://www.desperatesailors.com/templates/Live/media/mapicons/info.png',
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() +
'<br>Longitude: ' + location.lng() +
'<br>Only the first four decimal places needed'
});
infowindow.open(map,marker);
}
}
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
window.onload = initialize;
</script>
Your placeMarker function creates a new (empty) marker variable in the local scope.
function placeMarker(location) {
var marker , i ;
if ( marker ) {
It will always create a new marker. Change it to:
var marker = null;
function placeMarker(location) {
if ( marker ) {

update infowindows when calling again a xml file

Good morning.
I have the next code which put some markers in a map from a xml file, every 5 seconds I call again the xml file and I update the position of the markers, but the problem is that the infowindows are not updated. Does anyone knows how to update them=
Here you have the code:
//<![CDATA[
var side_bar_html = "";
var gmarkers = [];
var map = null;
var markerclusterer = null;
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
map.setZoom(map.getZoom()+2);
}
function initialize() {
// create the map
var myOptions = {
zoom: 12,
center: new google.maps.LatLng(37.169619,-3.756981),
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
function getMarkers() {
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
downloadUrl("vehiculos.asp", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var imei = markers[i].getAttribute("imei");
var alias = markers[i].getAttribute("alias");
var speed= markers[i].getAttribute("speed");
var timestamp= markers[i].getAttribute("timestamp");
var estado= markers[i].getAttribute("estado");
var conectado= markers[i].getAttribute("conectado");
var altitude= markers[i].getAttribute("altitude");
var angle= markers[i].getAttribute("angle");
var html="<b>"+alias+" "+speed+" km/h <br/> "+timestamp;
var marker = createMarker(point,alias+" "+imei,html,estado,alias, speed, timestamp, altitude, angle);
}
markerCluster = new MarkerClusterer(map, gmarkers);
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,60)
});
setInterval(function updateMarkers() {
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
downloadUrl("vehiculos.asp", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var imei = markers[i].getAttribute("imei");
var alias = markers[i].getAttribute("alias");
var speed= markers[i].getAttribute("speed");
var timestamp= markers[i].getAttribute("timestamp");
var estado= markers[i].getAttribute("estado");
var conectado= markers[i].getAttribute("conectado");
var altitude= markers[i].getAttribute("altitude");
var angle= markers[i].getAttribute("angle");
var html="<b>"+alias+" a "+speed+" km/h <br/> "+timestamp;
var newLatLng = gmarkers[i].setPosition(point,alias+" "+imei,html,estado,alias,speed,timestamp,altitude,angle);
}
markerCluster = new MarkerClusterer(map, gmarkers);
});
}, 5000);
//finish updateMarkers
function createMarker(latlng, imei, html, estado, alias, speed, timestamp, altitude, angle) {
if(estado == 1)
image = '/artworks/icons/truck_green3.png';
else
image = '/artworks/icons/truck_red.png';
var textoLabel= alias+" speed: "+ speed+" km/h";
var contentString = html;
var newLatLng = new MarkerWithLabel({
position: latlng,
icon: image,
// map: map,
draggable: true,
flat: true,
labelContent: textoLabel,
labelAnchor: new google.maps.Point(40, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {
opacity: 0.50
},
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(newLatLng, 'click', function() {
infowindow.setContent(timestamp + alias);
infowindow.open(map,newLatLng);
});
gmarkers.push(newLatLng);
// side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + imei +'<\/a><br>';
}
You are not assigning the event handler in the setInterval function, so no infowindows.
Add this code to the setInterval() after creating the marker
google.maps.event.addListener(newLatLng, 'click', function() {
infowindow.setContent(timestamp + alias);
infowindow.open(map,newLatLng);
This may result in a closure problem as you are in a loop. So you can do something like the solutions in this Passing values in for loop to event listeners- Javascript.

Google Map v3 Getting center of circle?

i'm using google v3 js and i am trying to get the center of the circle whenever the person drag the circle or expand the circle. currently i do not know any event that is able to tigger that
<script type="text/javascript">
var latt = 1.3738459931841047;
var longg = 103.79745483398437;
var radius = 1000;
function alertame(lat, long) {
document.getElementById("<%= lblLatitute.ClientID %>").textContent = lat;
document.getElementById("<%= lblLongitude.ClientID %>").textContent = long;
latt = lat;
longg = long;
}
function show_alert() {
alert(latt + "hello"+radius);
}
function initialize() {
var myOptions = {
center: new google.maps.LatLng(1.3738459931841047, 103.79745483398437),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var circleOptions = {
center: new google.maps.LatLng(latt, longg),
radius: radius,
map: map,
editable: true
};
var circle = new google.maps.Circle(circleOptions);
google.maps.event.addListener(circle, 'radius_changed', function () {
radius = circle.getRadius();
alert("test");
});
google.maps.event.addListener(circle, 'drag', function () {
alert("test");
});
circle.setMap(map);
}
</script>
<style type="text/css">
.style1
{
width: 124px;
}
</style>
Solved by using the below
<script type="text/javascript">
var latt = 1.3738459931841047;
var longg = 103.79745483398437;
var radius = 1000;
var marker;
function show_alert() {
alert(latt + "hello"+radius);
}
function initialize() {
document.getElementById("<%= lblLatitute.ClientID %>").textContent = latt;
document.getElementById("<%= lblLongitude.ClientID %>").textContent = longg;
document.getElementById("<%= lblRadius.ClientID %>").textContent = radius;
var myOptions = {
center: new google.maps.LatLng(1.3738459931841047, 103.79745483398437),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var circleOptions = {
center: new google.maps.LatLng(latt, longg),
radius: radius,
map: map,
editable: true
};
var circle = new google.maps.Circle(circleOptions);
google.maps.event.addListener(circle, 'radius_changed', function () {
radius = circle.getRadius();
latt = circle.getCenter().lat();
longg = circle.getCenter().lng();
document.getElementById("<%= lblRadius.ClientID %>").textContent = radius;
});
marker = new google.maps.Marker({
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
position: new google.maps.LatLng(latt, longg),
});
circle.setMap(map);
google.maps.event.addListener(marker, 'dragstart', function() {
circle.setMap(null);
});
google.maps.event.addListener(marker, 'dragend', function() {
latt= marker.getPosition().lat();
longg = marker.getPosition().lng();
circle.setCenter(new google.maps.LatLng(latt, longg));
document.getElementById("<%= lblLatitute.ClientID %>").textContent = latt;
document.getElementById("<%= lblLongitude.ClientID %>").textContent = longg;
circle.setMap(map);
});
}
function toggleBounce() {
}
</script>
In short:
var latitude = circle.center.lat();
var longitude = circle.center.lng();
I think you might be looking for the events center_changed and radius_changed.
You can find all available events on the events table of google.maps.Circle class documentation page.

Resources