Getting updated coords when polyline/polygon vertex moved. (Google Maps) - html

I've figured out how to grab the coords when a polyline or polygon is added or a vertex is deleted, but I can't seem to apply how to catch when a polyline or polygon vertex is moved (vertex only, I have dragging entire poly's disabled intentionally). I'm using this link as a reference: event after modifying polygon in google maps api v3
Here is my complete HTML code (posted at pastebin for the sake of the reader):
http://pastebin.com/95HcHqQR
Here is the section I'm trying to make catch moves:
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
var newShape = e.overlay;
newShape.type = e.type;
if (e.type !== google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
///////////////////////////////////////////////////////////
//This section is intended to catch vertex moves...currently not
google.maps.event.addListener(newShape, 'polygoncomplete', function(e) {
google.maps.event.addListener(newShape.getPath(), 'set_at', function(e) {
google.maps.event.addListener(newShape.getPath(), 'insert_at', function(e) {
var path = newShape.getPaths().getAt(e.path);
document.getElementById("polygonEditTest").value += path.getAt(e.vertex) + '\n';
})
});
});
google.maps.event.addListener(newShape, 'polylinecomplete', function(e) {
google.maps.event.addListener(newShape.getPath(), 'set_at', function(e) {
google.maps.event.addListener(newShape.getPath(), 'insert_at', function(e) {
var path = newShape.getPaths().getAt(e.path);
document.getElementById("polylineEditTest").value += path.getAt(e.vertex) + '\n';
})
});
});
///////////////////////////////////////////////////////////
// Add an event listener that selects the newly-drawn shape when the user
// clicks it.
google.maps.event.addListener(newShape, 'click', function(e) {
if (e.vertex !== undefined) {
if (newShape.type === google.maps.drawing.OverlayType.POLYGON) {
var path = newShape.getPaths().getAt(e.path);
path.removeAt(e.vertex);
/////////////////////////////////////////////////////////////
//Update textboxes with geo data when polygon vertex deleted
document.getElementById("action_gon").value = ''
document.getElementById("action_gon").value += "#polygon vertex deleted\n";
for (var i = 0; i < path.length; i++) {
document.getElementById("action_gon").value += path.getAt(i) + '\n';
}
//
if (path.length < 3) {
newShape.setMap(null);
document.getElementById("action_gon").value = 'This box shows coords when a new POLYGON shape is added and/or vertex deleted'
}
}
if (newShape.type === google.maps.drawing.OverlayType.POLYLINE) {
var path = newShape.getPath();
path.removeAt(e.vertex);
/////////////////////////////////////////////////////////////
//Update textboxes with geo data when polyline vertex deleted
document.getElementById("action_line").value = ''
document.getElementById("action_line").value += "#polyline vertex deleted\n";
for (var i = 0; i < path.length; i++) {
document.getElementById("action_line").value += path.getAt(i) + '\n';
}
//
if (path.length < 2) {
newShape.setMap(null);
document.getElementById("action_line").value = 'This box shows coords when a new POLYLINE shape is added and/or vertex deleted'
}
}
}
setSelection(newShape);
});
setSelection(newShape);
} else {
google.maps.event.addListener(newShape, 'click', function(e) {
setSelection(newShape);
});
setSelection(newShape);
}
});
EDIT: Here is what I believe to be the minimal code needed to demonstrate the problem (inability to capture vertex moves).
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<title>Test</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=drawing,places"></script>
<style type="text/css">
#map, html, body {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
}
</style>
<script type="text/javascript">
//Map Specifications
function initialize () {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 18,
center: new google.maps.LatLng(33.27144940863937, -117.2983479390361),
mapTypeId: google.maps.MapTypeId.HYBRID,
disableDefaultUI: true,
zoomControl: true,
mapTypeControl: false,
scaleControl: true,
streetViewControl: true,
rotateControl: true,
fullscreenControl: false
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true,
draggable: false
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers and lines
drawingManager = new google.maps.drawing.DrawingManager({
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYLINE,
google.maps.drawing.OverlayType.POLYGON
]
},
markerOptions: {
draggable: false
},
polylineOptions: {
editable: true,
draggable: false
},
//rectangleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
//////////////////////////////////////////
var drawingManager;
var selectedShape;
function clearSelection () {
if (selectedShape) {
if (selectedShape.type !== 'marker') {
selectedShape.setEditable(false);
}
selectedShape = null;
}
}
function setSelection (shape) {
if (shape.type !== 'marker') {
clearSelection();
shape.setEditable(true);
}
selectedShape = shape;
}
//////////////////////////////////////////
google.maps.event.addListener(drawingManager, 'overlaycomplete', function (e) {
var newShape = e.overlay;
newShape.type = e.type;
if (e.type !== google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
google.maps.event.addListener(newShape, 'polygoncomplete', function (e) {
google.maps.event.addListener(newShape.getPath(), 'set_at', function() {
google.maps.event.addListener(newShape.getPath(), 'insert_at', function() {
var path = newShape.getPaths().getAt(e.path);
document.getElementById("polygonEditTest").value += path.getAt(e.vertex) + '\n';
})
});
});
google.maps.event.addListener(newShape, 'polylinecomplete', function (e) {
google.maps.event.addListener(newShape.getPath(), 'set_at', function(e) {
google.maps.event.addListener(newShape.getPath(), 'insert_at', function(e) {
var path = newShape.getPaths().getAt(e.path);
document.getElementById("polylineEditTest").value += path.getAt(e.vertex) + '\n';
})
});
});
// Add an event listener that selects the newly-drawn shape when the user
// clicks it.
setSelection(newShape);}
else {
google.maps.event.addListener(newShape, 'click', function (e) {
setSelection(newShape);
});
setSelection(newShape);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="geoinfoboxes">
<textarea id="polylineEditTest" rows="8" cols="46">This box shows coords for edited POLYLINES (ie. moving a vertex)</textarea>
<textarea id="polygonEditTest" rows="8" cols="46">This box shows coords for edited POLYGONS (ie. moving a vertex)</textarea>
</div>
<div id="map"></div>
</body>
</html>

To listen for the drag of an editable polygon's vertex drag, use an MCVArray set_at event listener:
google.maps.event.addListener(polygon.getPath(), 'set_at', processVertex);
google.maps.event.addListener(polygon.getPath(), 'insert_at', processVertex);
function processVertex(e) {
var logStr = ""
for (var i = 0; i < this.getLength(); i++) {
logStr += this.getAt(i).toUrlValue(6) + " ";
}
console.log(logStr);
}
proof of concept fiddle
code snippet:
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var polygon = new google.maps.Polygon({
path: [new google.maps.LatLng(37.4544762, -122.1161696),
new google.maps.LatLng(37.3751, -122.1731859),
new google.maps.LatLng(37.4274745, -122.169719)
],
map: map,
editable: true
});
google.maps.event.addListener(polygon.getPath(), 'set_at', processVertex);
google.maps.event.addListener(polygon.getPath(), 'insert_at', processVertex);
function processVertex(e) {
var logStr = ""
for (var i = 0; i < this.getLength(); i++) {
logStr += this.getAt(i).toUrlValue(6) + " ";
}
console.log(logStr);
}
}
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>

Related

Draw and delete polygon in google map

I try to draw polygon on button click and delete polygon from another button, it's working fine first time but after delete I can't draw another polygon. Please guide me. Here is code snippet:
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true,
fillColor: '#FF1493'
};
var selectedShape;
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: false,
markerOptions: {
draggable: true
},
polygonOptions: polyOptions
});
$('#enablePolygon').click(function(){
drawingManager.setMap(map);
});
$('#resetPolygon').click(function(){
if (selectedShape) {
selectedShape.setMap(null);
}
drawingManager.setMap(null);
$('#showonPolygon').hide();
$('#resetPolygon').hide();
});
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
shape.setEditable(true);
}
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
all_overlays.push(e);
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
}
});
Here I show reset button on polygon complete event and try to find area of current polygon:
google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
// var area = google.maps.geometry.spherical.computeArea(selectedShape.getPath());
// $('#areaPolygon').html(area.toFixed(2)+' Sq meters');
$('#resetPolygon').show();
});
Here is HTML:
<input type="button" id="enablePolygon" value="Calculate Area" />
<input type="button" id="resetPolygon" value="Reset" style="display: none;" />
<div id="showonPolygon" style="display:none;"><b>Area:</b> <span id="areaPolygon"> </span></div>
You are setting the DrawingMode of the DrawingManager to null. When you re-enable the DrawingManager, you need to set it back to google.maps.drawing.OverlayType.POLYGON.
$('#enablePolygon').click(function() {
drawingManager.setMap(map);
drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
});
proof of concept fiddle
code snippet:
var geocoder;
var map;
var all_overlays = [];
function initialize() {
var 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 polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true,
fillColor: '#FF1493'
};
var selectedShape;
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: false,
markerOptions: {
draggable: true
},
polygonOptions: polyOptions
});
$('#enablePolygon').click(function() {
drawingManager.setMap(map);
drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
});
$('#resetPolygon').click(function() {
if (selectedShape) {
selectedShape.setMap(null);
}
drawingManager.setMap(null);
$('#showonPolygon').hide();
$('#resetPolygon').hide();
});
google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
// var area = google.maps.geometry.spherical.computeArea(selectedShape.getPath());
// $('#areaPolygon').html(area.toFixed(2)+' Sq meters');
$('#resetPolygon').show();
});
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
shape.setEditable(true);
}
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
all_overlays.push(e);
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input type="button" id="enablePolygon" value="Calculate Area" />
<input type="button" id="resetPolygon" value="Reset" style="display: none;" />
<div id="showonPolygon" style="display:none;"><b>Area:</b> <span id="areaPolygon"> </span>
</div>
<div id="map_canvas"></div>

How to remove previous shape when drawing new shape is started on Google Map

I am currently working on a map-based web application. Previous rectangle (or polygon) that is already drawn should be deleted before I draw new rectangle by drawing layer tool on Google Map.
There is "overlaycomplete" event on Google Map, but if I use it, previous rectangle is removed after drawing new rectangle is completed(mouse-up). However, I need to remove previous rectangle before process of drawing new rectangle starts(mouse-down). Two rectangle should not be seen at the same time on the map!
All feedbacks appreciated!
Here is jsFiddle! - http://jsfiddle.net/sean35/41Lrcq7L/30/
Example code:
function initialize() {
var centerInfo = document.getElementById("mainForm:centerInfo").value;
var zoomInfo = document.getElementById("mainForm:zoomInfo").value;
centerInfo = centerInfo.split(",");
var mapOptions = {
center : {
lat : parseFloat(centerInfo[0]),
lng : parseFloat(centerInfo[1])
},
zoom : parseInt(zoomInfo)
};
map = new google.maps.Map(document.getElementById('deviceControlMap'), mapOptions);
var drawingManager = new google.maps.drawing.DrawingManager({
// drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
drawingControl : true,
drawingControlOptions : {
position : google.maps.ControlPosition.TOP_CENTER,
drawingModes : [
// google.maps.drawing.OverlayType.POLYGON,
google.maps.drawing.OverlayType.RECTANGLE ]
},
rectangleOptions : {
strokeWeight : 1,
clickable : true,
editable : false,
zIndex : 1
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
if (event.type == google.maps.drawing.OverlayType.RECTANGLE) {
if(rectangle != null)
rectangle.setMap(null);
closeDimSubWin();
rectangle = event.overlay;
var bounds = rectangle.getBounds();
console.log(bounds);
}
});
google.maps.event.addListener(drawingManager, "drawingmode_changed", function() {
if(rectangle != null)
rectangle.setMap(null);
});
// when the user clicks somewhere else on the map.
google.maps.event.addListener(map, 'click', function() {
if(rectangle != null)
rectangle.setMap(null);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
EDIT: I wrote two similar question before. But I deleted them and wrote this question with extended information. I hope that the question is understandable.
One option:
set the drawing mode to null on rectanglecomplete
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
if (event.type == google.maps.drawing.OverlayType.RECTANGLE) {
if(rectangle != null)
rectangle.setMap(null);
rectangle = event.overlay;
var bounds = rectangle.getBounds();
console.log(bounds);
drawingManager.setDrawingMode(null);
}
});
remove the rectangle when it is changed back to RECTANGLE
google.maps.event.addListener(drawingManager, "drawingmode_changed", function() {
if ((drawingManager.getDrawingMode() == google.maps.drawing.OverlayType.RECTANGLE) &&
(rectangle != null))
rectangle.setMap(null);
});
updated fiddle
code snippet:
/*
* declare map as a global variable
*/
var map;
var rectangle = null;
/*
* use google maps api built-in mechanism to attach dom events
*/
google.maps.event.addDomListener(window, "load", function() {
var mapOptions = {
center: new google.maps.LatLng(33.808678, -117.918921),
zoom: 4,
};
map = new google.maps.Map(document.getElementById('deviceControlMap'), mapOptions);
var drawingManager = new google.maps.drawing.DrawingManager({
// drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
// google.maps.drawing.OverlayType.POLYGON,
google.maps.drawing.OverlayType.RECTANGLE
]
},
rectangleOptions: {
strokeWeight: 1,
clickable: true,
editable: false,
zIndex: 1
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
if (event.type == google.maps.drawing.OverlayType.RECTANGLE) {
if (rectangle != null)
rectangle.setMap(null);
rectangle = event.overlay;
var bounds = rectangle.getBounds();
console.log(bounds);
drawingManager.setDrawingMode(null);
}
});
google.maps.event.addListener(drawingManager, "drawingmode_changed", function() {
if ((drawingManager.getDrawingMode() == google.maps.drawing.OverlayType.RECTANGLE) &&
(rectangle != null))
rectangle.setMap(null);
});
// when the user clicks somewhere else on the map.
google.maps.event.addListener(map, 'click', function() {
if (rectangle != null)
rectangle.setMap(null);
});
});
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=drawing"></script>
<div id="deviceControlMap" style="height: 400px;"></div>

Ionic Framework-Can't move or drag the map in wp8

I have a main menu and an item to access the map view. for the first time the map is run according to expectation. the map also can zoom in-out, centerOnMe, and I can give a marker to the position. But when I move or drag the map, the map view was close suddenly and back to main menu. and when I try to access the map again, the map view show but with the main menu view half of it.
Here is my js code :
angular.module('starter.controllers')
.controller('LokasiBayarCtrl', function($scope, $ionicLoading, $location, $compile) {
$scope.go = function(path) {
$location.path(path);
};
var map, infoWindow, mapservice,
myLatlng = new google.maps.LatLng(-33.8668283734, 151.2064891821),
mapOptions = {
//center: myLatlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
},
iconsBase = 'img/marker/',
icons = {
atm: { icon: iconsBase + 'pln.png' }
};
// Marker + infowindow + angularjs compiled ng-click
var contentString = "<div><a ng-click='clickTest()'>Click me!</a></div>";
var compiled = $compile(contentString)($scope);
var mapHeight = Math.round( 3 / 5 * window.SCREEN_HEIGHT );
mapHeight = ( window.SCREEN_HEIGHT < 500 ) ? 240 : mapHeight;
$scope.mapHeight = mapHeight;
console.log("map height: " + mapHeight + " screenH: " + window.SCREEN_HEIGHT);
function loading(){
$ionicLoading.show({
content: 'Getting current location...',
showBackdrop: false //true
});
}
function loadingDone(){ $ionicLoading.hide(); }
function centerOnMe(){
if(!$scope.map) {
return;
}
loading();
function successCb(pos) {
myLatlng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
$scope.map.setCenter(myLatlng);
var myPosMarker = new google.maps.Marker({
position: map.getCenter(),
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
draggable: false,
map: map
});
console.log(pos.coords);
console.log('centerOn Me :', map);
searchPlaces();
loadingDone();
}
function errorCb_highAccuracy(error){
console.log('errorCb_highAccuracy : Unable to get location: ' + error.message);
if (error.code == error.TIMEOUT) {
// Attempt to get GPS loc timed out after 5 seconds,
// try low accuracy location
console.log("attempting to get low accuracy location");
navigator.geolocation.getCurrentPosition(
successCb,
errorCb_lowAccuracy,
{maximumAge:600000, timeout:10000, enableHighAccuracy: false});
return;
}
var msg = "Can't get your location (high accuracy attempt). Error = ";
if (error.code == 1)
msg += "PERMISSION_DENIED";
else if (error.code == 2)
msg += "POSITION_UNAVAILABLE";
msg += ", msg = "+error.message;
loadingDone();
console.log(msg);
}
function errorCb_lowAccuracy(error){
var msg = "Can't get your location (low accuracy attempt). Error = ";
if (error.code == 1)
msg += "PERMISSION_DENIED";
else if (error.code == 2)
msg += "POSITION_UNAVAILABLE";
else if (error.code == 3)
msg += "TIMEOUT";
msg += ", msg = "+error.message;
loadingDone();
console.log(msg);
alert(msg);
}
navigator.geolocation.getCurrentPosition(
successCb, errorCb_highAccuracy, {
maximumAge:600000, timeout:5000, enableHighAccuracy: true
});
}
function initialize() {
console.log('init');
map = new google.maps.Map(document.getElementById("map"),
mapOptions);
infoWindow = new google.maps.InfoWindow({
content: compiled[0]
});
mapservice = new google.maps.places.PlacesService(map);
$scope.map = map;
google.maps.event.addListener(map, 'bounds_changed', searchPlaces);
google.maps.event.addListener(map, 'zoom_changed', searchPlaces);
google.maps.event.addListener(map, 'center_changed', searchPlaces);
google.maps.event.addListener(map, 'resize', searchPlaces);
google.maps.event.addListener(map, 'idle', function () {
document.getElementById("map").setAttribute("style", "min-height: 240px; height: "+$scope.mapHeight+"px; position: relative; background-color: rgb(229, 227, 223); overflow: hidden; -webkit-transform: translateZ(0px);");
console.log(document.getElementById("map").getAttribute("style"));
var center = map.getCenter();
google.maps.event.trigger(map, 'resize');
map.setCenter(center);
});
centerOnMe();
}
function getPlaceData(result){
return {
name: result.name, address_fmt: result.formatted_address, icon: result.icon, types: result.types,
vicinity: result.vicinity, phone: result.formatted_phone_number, website: result.website
};
}
function searchPlaces(){
console.log('searchPlaces');
// nearby search
var request = {
location: myLatlng,
radius: '1000',
types: ['atm', 'bank'],
rankby: 'prominence'
};
mapservice.nearbySearch(request, searchCb);
}
function searchCb(results, status){
if (status != google.maps.places.PlacesServiceStatus.OK) {
console.log('error');
//alert(status);
console.log(status);
return;
}
console.log(results.length);
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
/*for (var i = 0, result; result = results[i]; i++) {
//if (i < 3) { console.log(result); }
console.log('success');
createMarker(result);
}*/
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon : icons['atm'].icon
});
google.maps.event.addListener(marker, 'click', function() {
mapservice.getDetails(place, function(result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
console.log(result);
infoWindow.setContent(result.name);
infoWindow.open(map, marker);
$scope.place = getPlaceData(result);
console.log($scope.place);
$scope.$apply(); // ZUL : quick and dirty
});
});
}
//google.maps.event.addDomListener(window, 'load', initialize);
$scope.centerOnMe = function() {
centerOnMe();
};
$scope.clickTest = function() {
alert('Example of infowindow with ng-click')
};
// main
initialize();
$scope.place = null;
});
Please can any one can tell me what's wrong with my code?
Previously I apologize because my english is bad, I would be grateful much if anyone can help me.

Get the lat lng when plotting the polygon points

I am trying to get the lat lng of the polygon while drawing the polygon on google map. Does anyone know what event is triggered when we plot the points of polygon.
Basically what I am trying to do is undo/redo function for the polygon. So when a user plots 2 points one then clicks undo then it should be able to delete 1 point on one click.
As the map click event is disabled while drawing a polygon how to get the lat lng points? Is it possible what I am trying to do? Can anyone please help me with this? Any links or examples that I could refer to?
Below is my code to draw polygon:
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: false,
polygonOptions: {
strokeWeight: 2,
fillOpacity: 0.2,
editable: true,
fillColor: '#FFF000',
strokeColor: '#FFF000',
geodesic: true,
suppressUndo: true
},
polylineOptions: {
editable: false,
suppressUndo: true
}
});
drawingManager.setMap(map);
Try this
var myPoly;
google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
myPoly = polygon;
get_coordinates(polygon);//call to get coordinates
//editing polygon function
google.maps.event.addListener(polygon.getPath(), 'set_at', function() {
get_coordinates(polygon);//call to get coordinates
});
var newShape = polygon.overlay;
//newShape.type = polygon.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
});
and the get coordinate function
//function to get coordinates of polygon
function get_coordinates(polygon){
var full_path = [];//initialize array for set coordinates.
polygon.getPath().forEach(function(elem, index){
full_path.push(elem.toUrlValue());
});
return full_path;
}
ok. I can give you all the functions you need. You can integrate last code with the following. And you cannot delete any point but replace it.
var drawingManager;
var selectedShape;
var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
var selectedColor;
var colorButtons = {};
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
shape.setEditable(true);
selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}
function deleteSelectedShape() {
if (selectedShape) {
selectedShape.setMap(null);
}
}
function selectColor(color) {
selectedColor = color;
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
}
// Retrieves the current options from the drawing manager and replaces the
// stroke or fill color as appropriate.
var polylineOptions = drawingManager.get('polylineOptions');
polylineOptions.strokeColor = color;
drawingManager.set('polylineOptions', polylineOptions);
var rectangleOptions = drawingManager.get('rectangleOptions');
rectangleOptions.fillColor = color;
drawingManager.set('rectangleOptions', rectangleOptions);
var circleOptions = drawingManager.get('circleOptions');
circleOptions.fillColor = color;
drawingManager.set('circleOptions', circleOptions);
var polygonOptions = drawingManager.get('polygonOptions');
polygonOptions.fillColor = color;
drawingManager.set('polygonOptions', polygonOptions);
}
function setSelectedShapeColor(color) {
if (selectedShape) {
if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
selectedShape.set('strokeColor', color);
} else {
selectedShape.set('fillColor', color);
}
}
}
function makeColorButton(color) {
var button = document.createElement('span');
button.className = 'color-button';
button.style.backgroundColor = color;
google.maps.event.addDomListener(button, 'click', function() {
selectColor(color);
setSelectedShapeColor(color);
});
return button;
}
function buildColorPalette() {
var colorPalette = document.getElementById('color-palette');
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
var colorButton = makeColorButton(currColor);
colorPalette.appendChild(colorButton);
colorButtons[currColor] = colorButton;
}
selectColor(colors[0]);
}
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(22.344, 114.048),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers, lines, and shapes.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
markerOptions: {
draggable: true
},
polylineOptions: {
editable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
}
});
// Clear the current selection when the drawing mode is changed, or when the
// map is clicked.
google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
google.maps.event.addListener(map, 'click', clearSelection);
google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);
buildColorPalette();
}
google.maps.event.addDomListener(window, 'load', initialize);

Disable point-of-interest information window using Google Maps API v3

I have a custom map with an information bubble and custom markers. When I zoom into points of interest such as parks and universities appear and when I click an information window opens. How do I disable the info window?
My code is as follows:
var geocoder;
var map;
var infoBubble;
var dropdown = "";
var gmarkers = [];
var hostel_icon = new google.maps.MarkerImage('/resources/hostel_blue_icon.png',
new google.maps.Size(28,32),
new google.maps.Point(0,0),
new google.maps.Point(14,32));
var bar_icon = new google.maps.MarkerImage('/resources/bar_red_icon.png',
new google.maps.Size(28,32),
new google.maps.Point(0,0),
new google.maps.Point(14,32));
var icon_shadow = new google.maps.MarkerImage('/resources/myicon_shadow.png',
new google.maps.Size(45,32),
new google.maps.Point(0,0),
new google.maps.Point(12,32));
var customIcons = {
hostel: {
icon: hostel_icon,
shadow: icon_shadow
},
bar: {
icon: bar_icon,
shadow: icon_shadow
}
};
function initialize() {
var latlng = new google.maps.LatLng(12.82364, 26.29987);
var myMapOptions = {
zoom: 2,
center: latlng,
panControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.TERRAIN,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR},
navigationControlOptions: {style: google.maps.NavigationControlStyle.DEFAULT}
}
map = new google.maps.Map(document.getElementById("map_canvas"), myMapOptions);
infoBubble = new InfoBubble({
shadowStyle: 0,
padding: 0,
backgroundColor: 'rgb(57,57,57)',
borderRadius: 5,
arrowSize: 10,
borderWidth: 1,
maxWidth: 400,
borderColor: '#2c2c2c',
disableAutoPan: false,
hideCloseButton: true,
arrowPosition: 50,
backgroundClassName: 'phoney',
arrowStyle: 0
});
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml_2.php", function(data) {
var xml = parseXml(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var bar_name = markers[i].getAttribute("bar_name");
var hostel_name = markers[i].getAttribute("hostel_name");
var street = markers[i].getAttribute("street");
var city = markers[i].getAttribute("city");
var postcode = markers[i].getAttribute("postcode");
var country = markers[i].getAttribute("country");
var page = markers[i].getAttribute("page");
var map_photo = markers[i].getAttribute("map_photo");
var type = markers[i].getAttribute("type");
var category = markers[i].getAttribute("category");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = '<div class="infowindow"><div class="iwPhoto" style="width: 105px; height: 65px;">' + "' + "<a href='" + page + "'>" + hostel_name + "" + '</div><div class="iwCategory" style="height: 15px;">' + category + '</div><div class="iwCity" style="height: 29px;">' + "' + "<a href='" + page + "'><img src='/resources/arrow.png'/>" + '</div></div></div>';
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow,
title: bar_name
});
marker.bar_name = bar_name;
marker.category = category;
bindInfoBubble(marker, map, infoBubble, html, bar_name);
gmarkers.push(marker);
str = '<option selected> - Select a club - </option>';
for (j=0; j < gmarkers.length; j++){
str += '<option value="'+gmarkers[j].bar_name+'">'+gmarkers[j].bar_name+', '+gmarkers[j].category+'</option>';
}
var str1 ='<form name="form_city" action=""><select style="width:150px;" id="select_city" name="select_cityUrl" onchange="handleSelected(this);">';
var str2 ='</select></form>';
dropdown = str1 + str + str2;
}
document.getElementById("dd").innerHTML = dropdown;
});
}
function handleSelected(opt) {
var indexNo = opt[opt.selectedIndex].index;
google.maps.event.trigger(gmarkers[indexNo-1], "click");
}
function bindInfoBubble(marker, map, infoBubble, html) {
google.maps.event.addListener(marker, 'click', function() {
infoBubble.setContent(html);
infoBubble.open(map, marker);
google.maps.event.addListener(map, "click", function () {
infoBubble.close();
});
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
UPDATE Google Maps JavaScript API V3
You can set clickableIcons to false in MapOptions. This will keep the POI icons but disable the infowindows just as you want.
function initialize() {
var myMapOptions = { clickableIcons: false }
}
Further details here...
https://developers.google.com/maps/documentation/javascript/3.exp/reference#MapOptions
See the other answers for the clickable: false answer.
However, if you want it clickable, but no infowindow, call stop() on the event to prevent the infowindow from showing, but still get the location info:
map.addListener('click', function (event) {
// If the event is a POI
if (event.placeId) {
// Call event.stop() on the event to prevent the default info window from showing.
event.stop();
// do any other stuff you want to do
console.log('You clicked on place:' + event.placeId + ', location: ' + event.latLng);
}
}
For more info, see the docs.
Other option: completely remove the POI-icons, and not only the infoWindow:
var mapOptions = {
styles: [{ featureType: "poi", elementType: "labels", stylers: [{ visibility: "off" }]}]
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
You can do this by creating a styled map without labels for the points of interest.
This maintains the topography and other nice pieces of information on the map, but removes the markers.
var remove_poi = [
{
"featureType": "poi",
"elementType": "labels",
"stylers": [
{ "visibility": "off" }
]
}
]
map.setOptions({styles: remove_poi})
You could consider the following approach to disable POI Info Window:
function disablePOIInfoWindow(){
var fnSet = google.maps.InfoWindow.prototype.set;
google.maps.InfoWindow.prototype.set = function () {
};
}
Example
function initMap() {
var latlng = new google.maps.LatLng(40.713638, -74.005529);
var myOptions = {
zoom: 17,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
disablePOIInfoWindow();
}
function disablePOIInfoWindow(){
var fnSet = google.maps.InfoWindow.prototype.set;
google.maps.InfoWindow.prototype.set = function () {
alert('Ok');
};
}
google.maps.event.addDomListener(window, 'load', initMap);
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
height: 100%;
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<div id="map_canvas"></div>
The above example affects all the info windows, so if you need to disable only POI Info Window, then we could introduce flag to determine whether it is POI Info Window or not:
function disablePOIInfoWindow(){
var fnSet = google.maps.InfoWindow.prototype.set;
google.maps.InfoWindow.prototype.set = function () {
if(this.get('isCustomInfoWindow'))
fnSet.apply(this, arguments);
};
}
Example
function initMap() {
var latlng = new google.maps.LatLng(40.713638, -74.005529);
var myOptions = {
zoom: 17,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infowindow = new google.maps.InfoWindow({
content: ''
});
infowindow.set('isCustomInfoWindow',true);
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
disablePOIInfoWindow();
google.maps.event.addListener(map, 'click', function (event) {
infowindow.setContent(event.latLng.lat() + "," + event.latLng.lng());
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
function disablePOIInfoWindow(){
var fnSet = google.maps.InfoWindow.prototype.set;
google.maps.InfoWindow.prototype.set = function () {
if(this.get('isCustomInfoWindow'))
fnSet.apply(this, arguments);
};
}
//google.maps.event.addDomListener(window, 'load', initMap);
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
height: 100%;
}
<div id="map_canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"
async defer></script>
Simply style the map to not show Points of Interest. This is simple and does not breach Google's terms of service.
eg
mapOpts = {
styles: [
{
featureType: "poi",
stylers: [
visibility: "off"
]
}
]
};
$("#my-map").gmap(mapOpts).on("init", function(evt, map){
// do stuff with the initialised map
});
If you want the data without getting the InfoWindow HTML showing at all, you simply have to re-work the prototype of google.maps.InfoWindow:
google.maps.InfoWindow.prototype.open = function () {
return this; //prevent InfoWindow to appear
}
google.maps.InfoWindow.prototype.setContent = function (content) {
if (content.querySelector) {
var addressHTML = content.querySelector('.address');
var address = addressHTML.innerHTML.replace(/<[^>]*>/g, ' ').trim();
var link = content.querySelector('a').getAttribute('href');
var payload = {
header: 'event',
eventName: 'place_picked',
data: {
name: content.querySelector('.title').innerHTML.trim(),
address: address,
link: link
}
};
console.log('emit your event/call your function', payload);
}
};
We can do it by handling clicks on poi, Google api has provided a way to detect clicks on POI as per this article
Based on article above Here is a simpler version of code that can be used to stop the clicks on POI
function initMap() {
map = new google.maps.Map(document.getElementById('map'), myOptions);
var clickHandler = new ClickEventHandler(map, origin);
}
var ClickEventHandler = function (map, origin) {
this.origin = origin;
this.map = map;
this.map.addListener('click', this.handleClick.bind(this));
};
ClickEventHandler.prototype.handleClick = function (event) {
//console.log('You clicked on: ' + event.latLng);
if (event.placeId) {
//console.log('You clicked on place:' + event.placeId);
// Calling e.stop() on the event prevents the default info window from
// showing.
// If you call stop here when there is no placeId you will prevent some
// other map click event handlers from receiving the event.
event.stop();
}
}