Integrating / adding Google Earth View to my map - google-earth

I am creating an interactive map for a non profit association "Friends of Knox Mountain Park" but I am getting trouble with the Google Earth view.
I've been searching on the web for weeks and none of the solutions I found works for me. Can someone take a look of the code and let me know what I should do to include Google Earth View in the map? Thanks in advance.
The online project: http://www.virtualbc.ca/knoxmountain/
And this is the javascript file (mapa2.js) containing the google map's code:
google.load('earth', '1');
var map;
var googleEarth;
var gmarkers = [];
var iconShadow = new google.maps.MarkerImage('icons/shadow.png',
new google.maps.Size(46, 42),
new google.maps.Point(0,0),
new google.maps.Point(13, 42));
var sites = [
['Apex Trail - Shelter',49.91174271, -119.48507050, 4, '<img src="images/apex_point_high.jpg">','magenta','14'],
['Apex Trail',49.91286999, -119.48413424, 3, '<img src="images/apex_point_low.jpg">','lemon','1'],
['Gordon Trail',49.91971281, -119.47954356, 2, '<img src="images/apex_point_low.jpg">','lemon','1'],
['Paul Tomb Bay',49.92555541, -119.47710250, 1, '<img src="images/tomb_bay.jpg">','lemon','1']
];
var infowindow = null;
var overlay;
// Used to make Google Map quard coords to MapCruncher/BingMaps quard coords
function TileToQuadKey ( x, y, zoom)
{
var quad = "";
for (var i = zoom; i > 0; i--)
{
var mask = 1 << (i - 1);
var cell = 0;
if ((x & mask) != 0)
cell++;
if ((y & mask) != 0)
cell += 2;
quad += cell;
}
return quad;
}
function init() {
var centerMap = new google.maps.LatLng(49.909671, -119.482241);
var myOptions = {
zoom: 10,
center: centerMap,
mapTypeId: google.maps.MapTypeId.SATELLITE
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Create the tile layers
// ASTER Tile Layer
myASTEROptions = {
getTileUrl : function (a,b) {
return "http://www.virtualbc.ca/knoxmountain/map/" + TileToQuadKey(a.x,a.y,b) + ".png";
},
isPng: true,
opacity: 1.0,
tileSize: new google.maps.Size(256,256),
name: "ASTER",
minZoom:13,
maxZoom:20
}
ASTERMapType = new google.maps.ImageMapType( myASTEROptions );
map.overlayMapTypes.insertAt(0, ASTERMapType);
// Aerial Tile Layer
myAerialOptions = {
getTileUrl : function (a,b) {
return "http://www.virtualbc.ca/knoxmountain/map/" + TileToQuadKey(a.x,a.y,b) + ".png";
},
isPng: true,
opacity: 1.0,
tileSize: new google.maps.Size(256,256),
name: "Aerial",
minZoom:15,
maxZoom:21
}
AerialMapType = new google.maps.ImageMapType( myAerialOptions );
map.overlayMapTypes.insertAt(1, AerialMapType);
var panorama = new google.maps.StreetViewPanorama(map.getDiv());
panorama.setVisible(false);
panorama.set('enableCloseButton', true);
map.setStreetView(panorama);
panorama.setPosition(centerMap);
setMarkers(map, sites);
setZoom(map, sites);
infowindow = new google.maps.InfoWindow({
content: "Loading..."
});
googleEarth = new GoogleEarth(map);
google.maps.event.addListenerOnce(map, 'tilesloaded', addOverlays);
}
/*
This functions sets the markers (array)
*/
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var site = markers[i];
var siteLatLng = new google.maps.LatLng(site[1], site[2]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
title: site[0],
zIndex: site[3],
html: site[4],
// Markers drop on the map
animation: google.maps.Animation.DROP,
icon: 'http://www.virtualbc.ca/knoxmountain/icons/icon.png',
shadow: iconShadow
});
gmarkers.push(marker);
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
}
/*
Set the zoom to fit comfortably all the markers in the map
*/
function setZoom(map, markers) {
var boundbox = new google.maps.LatLngBounds();
for ( var i = 0; i < markers.length; i++ )
{
boundbox.extend(new google.maps.LatLng(markers[i][1], markers[i][2]));
}
map.setCenter(boundbox.getCenter());
map.fitBounds(boundbox);
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i-1], "click");
}
google.maps.event.addDomListener(window, 'load', init);

The first issue I notice with your site is you are linking to http://www.virtualbc.ca/src/googleearth-compiled.js which does not exist.

Related

One pushpin click opens them all

Need help troubleshooting. All of the pushpins open upon clicking a single one opens up every pushpin infobox. I want there to be one pushpin infobox that changes each time a pushpin is clicked, only allowing one infobox to be open at a time.
// BING MAP Java Script
var map = null;
var pinid = 0;
var arrPinInfobox = [];
//Bing V8 start
function GetMap() { //LocInfo, Lat, Long
var _MapElement = document.getElementById("myMap");
if (_MapElement === null || typeof _MapElement === "undefined")
return;
if(jQuery("#pagesitemap_4_noMap").length < 0)
return;
var arrLocInfoRec = [];
var arrLLAdder = [];
var MapCenterLat;
var MapCenterLong;
var ZoomFactor;
var ZipLLSource = jQuery("#hdnZipLL").val();
var LocInfo = jQuery("#hdnCompleteLocInfo").val();
var ZipLL = [];
var Lat = "";
var Long ="";
console.log("Long");
if(typeof LocInfo === "undefined")
{
console.log("locInfo Undefined");
return;
}
if (ZipLLSource.length > 0) {
ZipLL = (ZipLLSource).split("`");
}
if (LocInfo.length > 0) {
arrLocInfoRec = LocInfo.split("|")
}
if (Lat.length > 0 && Long.length > 0) {
MapCenterLat = parseFloat(Lat);
MapCenterLong = parseFloat(Long);
ZoomFactor = 11; //16
}
else if (ZipLL.length >= 2) {
MapCenterLat = parseFloat(ZipLL[0]);
MapCenterLong = parseFloat(ZipLL[1]);
ZoomFactor = 11;
}
var mapOptions = {
credentials: ' ',
center: new Microsoft.Maps.Location(MapCenterLat, MapCenterLong),
mapTypeId: Microsoft.Maps.MapTypeId.Automatic,
zoom: ZoomFactor,
showScalebar: true
}
map = new Microsoft.Maps.Map('#myMap', mapOptions);
var arrPins = [];
var arrPinCenter = [];
//Generating Pins for multiple locations with Lat,Long
for (var locNum = 0; locNum <= arrLocInfoRec.length - 1; locNum++) {
try {
arrLLAdder = arrLocInfoRec[locNum].split("`");
if (arrLLAdder.length >= 13) {
//var latlong = arrLLAdder[11].split(',');
arrPinCenter[locNum] = new Microsoft.Maps.Location(parseFloat(arrLLAdder[11]), parseFloat(arrLLAdder[12]));
arrPinCenter[locNum] = new Microsoft.Maps.Location(parseFloat(arrLLAdder[11]), parseFloat(arrLLAdder[12]));
arrPins[locNum] = new Microsoft.Maps.Pushpin(
arrPinCenter[locNum], {
text: arrLLAdder[8] ,
icon: 'https://www.bingmapsportal.com/Content/images/poi_custom.png',
anchor: new Microsoft.Maps.Point(12, 39)
}
);
var adder = arrLLAdder[2] + '\r\n' + arrLLAdder[4] + '\r\n' + arrLLAdder[6] + arrLLAdder[9] + "\r\n" + arrLLAdder[1]
// Create the infobox for the pushpin
arrPinInfobox[locNum] = new Microsoft.Maps.Infobox(arrPins[locNum].getLocation(),
{ width: 350,
height: 100,
title: arrLLAdder[5],
description: adder,
offset: new Microsoft.Maps.Point(-3,13),
visible: false
});
// Add handler for the pushpin click event.
Microsoft.Maps.Events.addHandler(arrPins[locNum], 'click', displayInfobox);
// Add the Push Pins and InfoBox to the map all at once
if(arrPins.length > 0) {
map.entities.push(arrPins); //[locNum]
}
}
else {
console.log("Invalid Data: arrLocInfoRec[" + locNum + "] = \"" + arrLocInfoRec[locNum] + "\"");
}
} catch (e) {
console.log(e.message + "\r\n" + arrLocInfoRec[locNum]);
}
}
}
function displayInfobox(e) {
//map.entities.push(arrPinInfobox);
console.log("DisplayBox");
for(var i in arrPinInfobox){
arrPinInfobox[i].setOptions({ visible: true });
arrPinInfobox[parseInt(e.target.getText()) - 1].setOptions({ visible: true });
var infobox = arrPinInfobox[i];
infobox.setMap(map);
}
}
Your code in the displayInfobox function loops through all your infoboxes and sets visible to true and adding them to the map. Your code is functioning how it was written.
What you want to do is filter out your infoboxes. Personally I hate the whole array of infobox idea, it is messy. I believe I've recommended before the idea of creating a single infobox and reusing it when a pushpin is clicked. That is the best approach if you only need one infobox to appear at a time. If you want to be able to show multiple infoboxes at a time, store the reference to the infobox in the pushpin some how. All shapes in Bing Maps has a metadata property reserved for your custom data. Also just noticed you add the array of pushpins to the map several times, this will cause issues. Here is a proposed change to your code, I've added a comment with // Ricky: to indicate the changes I made:
// BING MAP Java Script
var map = null;
var pinid = 0;
var arrPinInfobox = [];
//Bing V8 start
function GetMap() { //LocInfo, Lat, Long
var _MapElement = document.getElementById("myMap");
if (_MapElement === null || typeof _MapElement === "undefined")
return;
if(jQuery("#pagesitemap_4_noMap").length < 0)
return;
var arrLocInfoRec = [];
var arrLLAdder = [];
var MapCenterLat;
var MapCenterLong;
var ZoomFactor;
var ZipLLSource = jQuery("#hdnZipLL").val();
var LocInfo = jQuery("#hdnCompleteLocInfo").val();
var ZipLL = [];
var Lat = "";
var Long ="";
console.log("Long");
if(typeof LocInfo === "undefined")
{
console.log("locInfo Undefined");
return;
}
if (ZipLLSource.length > 0) {
ZipLL = (ZipLLSource).split("`");
}
if (LocInfo.length > 0) {
arrLocInfoRec = LocInfo.split("|")
}
if (Lat.length > 0 && Long.length > 0) {
MapCenterLat = parseFloat(Lat);
MapCenterLong = parseFloat(Long);
ZoomFactor = 11; //16
}
else if (ZipLL.length >= 2) {
MapCenterLat = parseFloat(ZipLL[0]);
MapCenterLong = parseFloat(ZipLL[1]);
ZoomFactor = 11;
}
var mapOptions = {
credentials: ' ',
center: new Microsoft.Maps.Location(MapCenterLat, MapCenterLong),
mapTypeId: Microsoft.Maps.MapTypeId.Automatic,
zoom: ZoomFactor,
showScalebar: true
}
map = new Microsoft.Maps.Map('#myMap', mapOptions);
var arrPins = [];
var arrPinCenter = [];
//Generating Pins for multiple locations with Lat,Long
for (var locNum = 0; locNum <= arrLocInfoRec.length - 1; locNum++) {
try {
arrLLAdder = arrLocInfoRec[locNum].split("`");
if (arrLLAdder.length >= 13) {
//var latlong = arrLLAdder[11].split(',');
arrPinCenter[locNum] = new Microsoft.Maps.Location(parseFloat(arrLLAdder[11]), parseFloat(arrLLAdder[12]));
arrPins[locNum] = new Microsoft.Maps.Pushpin(arrPinCenter[locNum], {
text: arrLLAdder[8] ,
icon: 'https://www.bingmapsportal.com/Content/images/poi_custom.png',
anchor: new Microsoft.Maps.Point(12, 39)
});
var adder = arrLLAdder[2] + '\r\n' + arrLLAdder[4] + '\r\n' + arrLLAdder[6] + arrLLAdder[9] + "\r\n" + arrLLAdder[1]
// Create the infobox for the pushpin
//Ricky: Add your infobox as a reference in your pushpin
arrPins[locNum]. metadata = new Microsoft.Maps.Infobox(arrPins[locNum].getLocation(),
{ width: 350,
height: 100,
title: arrLLAdder[5],
description: adder,
offset: new Microsoft.Maps.Point(-3,13),
visible: false
});
// Add handler for the pushpin click event.
Microsoft.Maps.Events.addHandler(arrPins[locNum], 'click', displayInfobox);
}
else {
console.log("Invalid Data: arrLocInfoRec[" + locNum + "] = \"" + arrLocInfoRec[locNum] + "\"");
}
} catch (e) {
console.log(e.message + "\r\n" + arrLocInfoRec[locNum]);
}
}
// Add the Push Pins and InfoBox to the map all at once
//Ricky: Moved this out of the array as you only need to add array of pushpins to the map once.
if(arrPins.length > 0) {
map.entities.push(arrPins); //[locNum]
}
}
function displayInfobox(e) {
//map.entities.push(arrPinInfobox);
console.log("DisplayBox");
//Get infobox from the pushpin, rather than looping through array.
var infobox = e.target.metadata;
infobox.setOptions({ visible: true });
//for(var i in arrPinInfobox){
//arrPinInfobox[i].setOptions({ visible: true });
//arrPinInfobox[parseInt(e.target.getText()) - 1].setOptions({ visible: true });
//var infobox = arrPinInfobox[i];
//infobox.setMap(map);
//}
}
If you want to clean up your code some more I recommend:
get rid of all the array's, there is no need for them.
Use a layer for your pushpins. Add a single click event on the layer rather than on each individual pushpin.

Leaflet : Map container is already initialized

The User types some address (Hyderabad,Telanagna) on text field and clicks on Go button
I am fetching the latitude_res and longitude from google Map API as shown below
$(document).on('click', '.gobtn', function(event) {
$.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '', function(data) {
latitude_res = data.results[0].geometry.location.lat;
longitude_res = data.results[0].geometry.location.lng;
}).done(function() {
});
});
I am able to fetch the latitude and longitude , from google API say for example i got the following values
**17.385044
78.910965**
Then i am making a Ajax call again to fetch all the Markers present at this location in our Database .
And finally initializaing the map as shown below
initializeMap(lator,lonor,markers);
function initializeMap(lator, lonor, markers) {
var map = new L.Map('map_canvas', {
center: new L.LatLng(lator, lonor),
zoom: 5
});
var ggl = new L.Google();
var ggl2 = new L.Google('ROADMAP');
map.addLayer(ggl2);
if (markers.length > 0) {
var markers_leafcontainer = new L.MarkerClusterGroup();
var markersList = [];
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i].latitude);
var lng = parseFloat(markers[i].longititude);
var trailhead_name = markers[i].address;
var dealerId = markers[i].dealerID_db;
var dealername = markers[i].dealerName_db;
var contentString = "<html><body><div><p><h2>" + dealername + "</h2></p></div></body></html>";
var marker = L.marker(new L.LatLng(lat, lng), {}).on('click', onClick);
$(".howmanyfound").text(markers.length + ' Found');
markers_leafcontainer.addLayer(marker);
}
map.addLayer(markers_leafcontainer);
map.fitBounds(markers_leafcontainer.getBounds()); //set view on the cluster extent
}
}
Only for the first time this is working , from there on i am getting Uncaught Error: Map container is already initialized.
I am using leaflet with google Maps
So, don't initialize the map inside your function.
var map = new L.Map('map_canvas');
initializeMap(lator,lonor,markers);
function initializeMap(lator, lonor, markers) {
map.setView(L.latLng(lator, lonor));
}

Famo.us not loading Constructor of Strip View in Timbre Example

I am working no Timbre View Example of Famo.us, and what I am trying to achieve is simply open the page by clicking on strip view options in the app and closing the Menu Drawer as soon as I click on the Strip View option
for achieving this functionality I've read the Broad Cast and Listing from the Famo.us documentation. and wrote the following code in my example.
1) created a function to Broadcasting from an event handler with emit method and called it in Constructor of the Strip View.
Strip View:
define(function(require, exports, module) {
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
var Transform = require('famous/core/Transform');
var StateModifier = require('famous/modifiers/StateModifier');
var ImageSurface = require('famous/surfaces/ImageSurface');
var HeaderFooter = require('famous/views/HeaderFooterLayout');
var FastClick = require('famous/inputs/FastClick');
var check = true;
Boolean(check);
function StripView() {
View.apply(this, arguments);
_createBackground.call(this);
_createIcon.call(this);
_createTitle.call(this);
_setListenersForStripView.call(this);
}
StripView.prototype = Object.create(View.prototype);
StripView.prototype.constructor = StripView;
StripView.DEFAULT_OPTIONS = {
width: 320,
height: 55,
angle: -0.2,
iconSize: 32,
iconUrl: 'img/strip-icons/famous.png',
title: 'Famo.us',
fontSize: 26,
onload: 'StripView()'
};
function allFunctions()
{
_createBackground();
_createIcon();
_createTitle();
}
function _createBackground() {
this.backgroundSurface = new Surface({
size: [this.options.width, this.options.height],
properties: {
backgroundColor: 'black',
boxShadow: '0 0 1px black'
}
});
var rotateModifier = new StateModifier({
transform: Transform.rotateZ(this.options.angle)
});
var skewModifier = new StateModifier({
transform: Transform.skew(0, 0, this.options.angle)
});
this.add(rotateModifier).add(skewModifier).add(this.backgroundSurface);
// this.backgroundSurface.on("touchend", function(){alert("Click caught")})
}
function _createIcon() {
var iconSurface = new ImageSurface({
size: [this.options.iconSize, this.options.iconSize],
content: this.options.iconUrl,
pointerEvents: 'none'
});
var iconModifier = new StateModifier({
transform: Transform.translate(24, 2, 0)
});
this.add(iconModifier).add(iconSurface);
// iconSurface.on("click", function(){alert("Click caught")})
}
function _createTitle() {
this.titleSurface = new Surface({
size: [true, true],
pointerEvents: 'none',
content: this.options.title,
properties: {
color: 'white',
fontFamily: 'AvenirNextCondensed-DemiBold',
fontSize: this.options.fontSize + 'px',
textTransform: 'uppercase',
// pointerEvents : 'none'
}
});
var titleModifier = new StateModifier({
transform: Transform.thenMove(Transform.rotateZ(this.options.angle), [75, -5, 0])
});
this.add(titleModifier).add(this.titleSurface);
}
function _setListenersForStripView() {
this.backgroundSurface.on('touchend', function() {
this._eventOutput.emit('menuToggleforStripView');
alert('clicked on title');
}.bind(this));
}
module.exports = StripView;
});
2) Then created a Trigger Method in App View
App View:
define(function(require, exports, module) {
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
var Modifier = require('famous/core/Modifier');
var Transform = require('famous/core/Transform');
var StateModifier = require('famous/modifiers/StateModifier');
var Easing = require('famous/transitions/Easing');
var Transitionable = require('famous/transitions/Transitionable');
var GenericSync = require('famous/inputs/GenericSync');
var MouseSync = require('famous/inputs/MouseSync');
var TouchSync = require('famous/inputs/TouchSync');
GenericSync.register({'mouse': MouseSync, 'touch': TouchSync});
var PageView = require('views/PageView');
var StripView = require('views/StripView');
var MenuView = require('views/MenuView');
var StripData = require('data/StripData');
function AppView() {
View.apply(this, arguments);
this.menuToggle = false;
this.pageViewPos = new Transitionable(0);
this.stripViewPos = new Transitionable(0);
_createPageView.call(this);
_StripView.call(this);
_createMenuView.call(this);
_setListeners.call(this);
_handleSwipe.call(this);
_setListenersForStripView.call(this);
}
AppView.prototype = Object.create(View.prototype);
AppView.prototype.constructor = AppView;
AppView.DEFAULT_OPTIONS = {
openPosition: 276,
transition: {
duration: 300,
curve: 'easeOut'
},
posThreshold: 138,
velThreshold: 0.75
};
function _createPageView() {
this.pageView = new PageView();
this.pageModifier = new Modifier({
transform: function() {
return Transform.translate(this.pageViewPos.get(), 0, 0);
}.bind(this)
});
this._add(this.pageModifier).add(this.pageView);
}
function _StripView() {
this.stripView = new StripView();
this.stripModifier = new Modifier({
transform: function() {
return Transform.translate(this.stripViewPos.get(), 0, 0);
}.bind(this)
});
this._add(this.stripModifier).add(this.stripView);
}
function _createMenuView() {
this.menuView = new MenuView({stripData: StripData});
var menuModifier = new StateModifier({
transform: Transform.behind
});
this.add(menuModifier).add(this.menuView);
}
function _setListeners() {
this.pageView.on('menuToggle', this.toggleMenu.bind(this));
}
function _setListenersForStripView() {
this.stripView.on('menuToggleforStripView', this.toggleMenu.bind(this));
}
function _handleSwipe() {
var sync = new GenericSync(
['mouse', 'touch'],
{direction: GenericSync.DIRECTION_X}
);
this.pageView.pipe(sync);
sync.on('update', function(data) {
var currentPosition = this.pageViewPos.get();
if (currentPosition === 0 && data.velocity > 0) {
this.menuView.animateStrips();
}
this.pageViewPos.set(Math.max(0, currentPosition + data.delta));
}.bind(this));
sync.on('end', (function(data) {
var velocity = data.velocity;
var position = this.pageViewPos.get();
if (this.pageViewPos.get() > this.options.posThreshold) {
if (velocity < -this.options.velThreshold) {
this.slideLeft();
} else {
this.slideRight();
}
} else {
if (velocity > this.options.velThreshold) {
this.slideRight();
} else {
this.slideLeft();
}
}
}).bind(this));
}
AppView.prototype.toggleMenu = function() {
if (this.menuToggle) {
this.slideLeft();
} else {
this.slideRight();
this.menuView.animateStrips();
}
};
AppView.prototype.slideLeft = function() {
this.pageViewPos.set(0, this.options.transition, function() {
this.menuToggle = false;
}.bind(this));
};
AppView.prototype.slideRight = function() {
this.pageViewPos.set(this.options.openPosition, this.options.transition, function() {
this.menuToggle = true;
}.bind(this));
};
module.exports = AppView;
});
now what this code does, is create another strip overlapping the previous strips and it only works on the newly created strip view but not on the other strips which means when it comes back to srip view it loads only the DEFAULT_OPTIONS of strip view because the strip which is being generated newly and overlaping is titled famo.us
Please let me know where I am going wrong and how can I open a new view in my application by closing menu drawer.
Do you have a folder named 'data' with the 'StripData.js' file on your famo.us project?
I'm asking because I downloaded the the Starter Kit and I didn't find that file inside.

select two markers & draw line between them in leaflet

I am very much new to leaflet.
I have multiple markers/circle Markers plotted on my map in leaflet.
now I have to draw line between two markers//circle Markers when I select them.
Can any one help in doing this.
var map = L.map('map').setView([51.49521, -0.10062], 13);
L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © CloudMade'
}).addTo(map);
// get all 6 points
var points = new Array(
[51.49346, -0.11518],
[51.49827, -0.06763],
[51.48331, -0.08154],
[51.52284, -0.09974],
[51.51932, -0.06695],
[51.50949, -0.1363]
);
// centerpoint
var centerPoint = new L.LatLng(51.49521, -0.10062);
var marker1 = L.marker([51.49521, -0.10062]).addTo(map);
// adding allo points to map
for (var i =0 ; i < points.length; i++)
{
// here I can use marker also(if solution is possible with markers)
L.circleMarker([points[i][0],points[i][1]]).addTo(map);
var point = new L.LatLng(points[i][0],points[i][1]);
var pointList = [point, centerPoint];
var firstpolyline = new L.Polyline(pointList, {
color: 'red',
weight: 5,
smoothFactor: 1
}).addTo(map);
}
You must store selection (however it can be polyline points or flag in your markers). When you select two or more markers you must add points to you polyline - it draws line on map, otherwise you must remove point from polyline. See details about polyline: http://leafletjs.com/reference.html#polyline.
See next code for example:
// Init map
var map = L.map('map').setView([53.902257, 27.561640], 13);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
// Init selection and lines logic
var selection = [];
var polyline = L.polyline([], {color: 'red'}).addTo(map);
var onClick = function () {
var index = selection.indexOf(this);
if (index !== -1) {
this.setRadius(10);
selection.splice(index, 1);
polyline.spliceLatLngs(index, 1);
} else {
this.setRadius(25);
selection.push(this);
polyline.addLatLng(this.getLatLng())
}
};
// Init circle markers
L.circleMarker([53.90, 27.56]).on('click', onClick).addTo(map);
L.circleMarker([53.92, 27.60]).on('click', onClick).addTo(map);
L.circleMarker([53.88, 27.60]).on('click', onClick).addTo(map);
// Init selection droping on ESC pressed
L.DomEvent.on(document, 'keydown', function (e) {
if (e.keyCode === 27) {
var oldSelection = selection.slice(0);
for (var i = 0, l = oldSelection.length; i < l; i++) {
oldSelection[i].fire('click');
}
}
});
UPD:
It's analogically, see updated code:
var map = L.map('map').setView([51.49521, -0.10062], 13);
L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © CloudMade'
}).addTo(map);
// get all 6 points
var points = [
[51.49346, -0.11518],
[51.49827, -0.06763],
[51.48331, -0.08154],
[51.52284, -0.09974],
[51.51932, -0.06695],
[51.50949, -0.1363]
];
// polyline
var selection = [];
var polyline = new L.Polyline([], {
color: 'red',
weight: 5,
smoothFactor: 1
}).addTo(map);
var changeMarkerState = function (marker, select) {
if (marker instanceof L.CircleMarker) {
if (select) {
marker.setRadius(25);
} else {
marker.setRadius(10);
}
}
if (marker instanceof L.Marker) {
if (select) {
marker.options.title = 'selected';
} else {
marker.options.title = 'unselected';
}
marker.setIcon(new L.Icon.Default());
}
};
var onClick = function () {
var index = selection.indexOf(this);
if (index !== -1) {
changeMarkerState(this, false);
selection.splice(index, 1);
polyline.spliceLatLngs(index, 1);
} else {
changeMarkerState(this, true);
selection.push(this);
polyline.addLatLng(this.getLatLng())
}
};
// centerpoint
var centerPoint = new L.LatLng(51.49521, -0.10062);
var marker1 = L.marker([51.49521, -0.10062],
{title: 'unselected'}).on('click', onClick).addTo(map);
// adding allo points to map
for (var i = 0, l = points.length; i < l; i++)
{
// here I can use marker also(if solution is possible with markers)
L.circleMarker(points[i]).on('click', onClick).addTo(map);
}

Google maps api v2 get polygon coordinate

I am a bit of a beginner at google maps api. I managed to let the user to draw a polygon on the map and then I want to get the coordinates on the drew polygon.
I have used the following segment of code but it gave me the following error Uncaught TypeError: Object [object Object] has no method 'getPath'
this is the code that I used
function startShape() {
initialize();
document.getElementById('lat').disabled = true;
document.getElementById('lng').disabled = true;
var polygon = new GPolygon([],"ff0000", 2, 0.7,"ff0000",0.2);
startDrawing(polygon, "Shape " + (++shapeCounter_), function() {
var cell = this;
var area = polygon.getArea();
cell.innerHTML = (Math.round(area / 10000) / 100) + "km<sup>2</sup>";
});
showcoor(polygon);
}
function startDrawing(poly, name, onUpdate) {
map.addOverlay(poly);
poly.enableDrawing(options);
poly.enableEditing({onEvent: "mouseover"});
poly.disableEditing({onEvent: "mouseout"});
GEvent.addListener(poly, "endline", function() {
//var cells = addFeatureEntry(name, color);
//GEvent.bind(poly, "lineupdated", cells.desc, onUpdate);
GEvent.addListener(poly, "click", function(latlng, index) {
if (typeof index == "number") {
poly.deleteVertex(index);
}
});
});
}
function showcoor (poly) {
GEvent.addListener(poly, "endline", function() {
GEvent.addListener(poly, "click", function() {
var str;
var vertices = this.getPath();
for (var i =0; i < vertices.length; i++) {
var xy = vertices.getAt(i);
str += xy.lat() +"," + xy.lng()+"<br />";
}
alert (str);
});
});
}
There is no getPath method on the GPolygon object. See the GPolygon reference.
Instead, you'll need to use getVertexCount() and getVertex(i).
for (var i = 0, I = this.getVertexCount(); i < I; ++i) {
var xy = this.getVertex(i);
str += xy.lat() + ', ' + xy.lng() + '<br />';
}