I have the following HTML and JS. When i click on the image the images zooms. This is working. But then I zoom out I want to retract the image to the original location when It was loaded.
Consider image being dragged to right a little and then zoomed.
What I want is when its zoomed out its relocated to the original location when it was loaded.
What am I doing wrong? I need the effect this page has here. When you drag the image and release it, it will go to its original position.
JS
var isZoom=1;
var stage=new Kinetic.Stage({
container:'container',
width:700,
height:700,
id:'kineticstage',
name:'kineticstage'
});
var layer=new Kinetic.Layer({});
var group = new Kinetic.Group({
width:700,
height:700,
draggable: true
});
layer.add(group);
// set the images
var pages = ["http://197.242.159.63/reader/demo/img/face.jpg"];
var loadedPage = 0;
function loadPage(pageno){
var imageObj = new Image();
imageObj.onload = function() {
var kimage = new Kinetic.Image({
x: 0,
y: 0,
image: imageObj,
width:700,
height:700
});
// add to layer
group.add(kimage);
stage.add(layer);
};
// load the page image
imageObj.src = pages[pageno - 1];
}
// page 1
loadPage(1);
var tween = new Kinetic.Tween({
node: group,
duration: 1.0,
rotation:0,
scaleX: 1.5,
scaleY: 1.5,
easing:Kinetic.Easings.EaseInOut
});
group.on('dblclick dbltap',function(e){
if(isZoom == 1){
tween.play();
}
else{
tween.reverse();
}
layer.batchDraw();
isZoom = (isZoom>0) ? -1 : 1;
});
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" >
<meta name="apple-mobile-web-app-capable" content="yes" >
</head>
<body>
<div id="container"><!-- --></div>
</body>
<script type="text/javascript" language="javascript" src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.0.min.js"></script>
</html>
Fiddle
Dragging your kinetic group will cause its x,y to change.
To "undo" the drag, just reset the group back to its original x,y position:
In your case, you created the group at its default position of 0,0 so reset like this:
group.setX(0);
group.setY(0);
Related
I'm using the drawing pad (pen tool) plugin of Jquery to draw with different colors and having an image in the canvas as background. My purpose is to have a button to clear the drawing over the canvas. The way I try to do it remove the background image along with the drawing. How can I keep the background and remove the drawing on clicking the clear button ?
My fiddle : https://jsfiddle.net/ub3s9go7/
<script>
$(document).ready(function() {
// set background
var urlBackground = 'https://picsum.photos/id/100/500/400';
var imageBackground = new Image();
imageBackground.src = urlBackground;
imageBackground.setAttribute('crossorigin', 'anonymous');
$("#target").drawpad();
var contextCanvas = $("#target canvas").get(0).getContext('2d');
imageBackground.onload = function(){
contextCanvas.drawImage(imageBackground, 0, 0);
}
// Need to clear only the drawing not the background image
$("#clearDrawing").click(function() {
contextCanvas.clearRect(0, 0, 750, 423);
});
});
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://cnbilgin.github.io/jquery-drawpad/jquery-drawpad.css" />
<style>
body {background-color:rgb(248, 255, 227)}
#target {
width:500px;
height:400px;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cnbilgin.github.io/jquery-drawpad/jquery-drawpad.js"></script>
</head>
<body>
<button id="clearDrawing">Clear Drawing</button>
<div id="target" class="drawpad-dashed"></div>
</body>
</html>
This answer is an improvisation on my previous answer at https://stackoverflow.com/a/67155647/3706717
So we have new requirement: delete/clear previous drawings
There are some possible approach here:
#sinisake in comment suggested to reload the background so that we have fresh canvas with only the background intact (but for some reason, white doodle make the background gone)
the library must have "delete" or "erase" doodle feature (which it didn't have)
save each changes of the drawing when user click "save", so that user can "undo" to previous version of the drawing (like git's git commit and git reset command), I'll be using this approach in my answer
Ideally, you should use server-side language and persistent storage (e.g.: database) to store user's doodling history. But in this case, to simulate such thing I'll be using javascript's localStorage API https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
So every time I'm calling localStorage API, just assume that I'm calling some ajax to some endpoint.
Fiddle: https://jsfiddle.net/0da572jy/3/
Here is stack fiddle (modified because browser didn't allow stack fiddle to use localStorage)
// polyfill for localStorage API
var localStorage1 = {
items: {},
removeItem: function(key) {
window.localStorage1.items[key] = null;
},
getItem: function(key) {
return window.localStorage1.items[key];
},
setItem: function(key, val) {
return window.localStorage1.items[key] = val;
},
}
//window.localStorage = localStorage1;
window.localStorage1 = localStorage1;
$(document).ready(function() {
$("#save").click(function() {
// I already explained the #save logic in https://stackoverflow.com/a/67155647/3706717
//console.log("save");
var base64Image = $("#target canvas").get(0).toDataURL();
//console.log(base64Image);
$("#outputBase64FormInput").val(base64Image);
$("#outputBase64").html(base64Image);
// load/read saved states/histories
var savedImageJson = window.localStorage1.getItem("savedImage");
//console.log(savedImageJson);
// if the history is undefined, create empty array
if(savedImageJson == null || typeof savedImageJson == "undefined") savedImageJson = "[]";
// parse the history
var savedImageArr = JSON.parse(savedImageJson);
// add current state as a new item to history
savedImageArr.push(base64Image);
// save the modified (added history)
window.localStorage1.setItem("savedImage", JSON.stringify(savedImageArr));
$("#numOfSavedHistory").html( savedImageArr.length );
});
// clear button just clears the localStorage (or any kind of API you use for persistent storage
$("#clear").click(function() {
//console.log("save");
window.localStorage1.removeItem("savedImage");
$("#numOfSavedHistory").html( 0 );
});
// undo last change (rollback to last state when you clicked save)
$("#undo").click(function() {
// clear canvas (to prevent white ink bug that also clears the background)
canvas.width = canvas.width;
//console.log("undo");
// load/read saved states/histories
var savedImageJson = window.localStorage1.getItem("savedImage");
//console.log(savedImageJson);
// if the history is undefined, create empty array
if(savedImageJson == null || typeof savedImageJson == "undefined") savedImageJson = "[]";
// parse the history
var savedImageArr = JSON.parse(savedImageJson);
// delete last item in history
savedImageArr.pop();
// save the modified (pop'ed history)
window.localStorage1.setItem("savedImage", JSON.stringify(savedImageArr));
// draw old picture on canvas
var imageOld = new Image();
imageOld.src = savedImageArr[savedImageArr.length-1];
imageOld.onload = function() {
contextCanvas.drawImage(imageOld, 0, 0);
};
$("#numOfSavedHistory").html( savedImageArr.length );
});
// set background
var urlBackground = 'https://picsum.photos/id/100/500/400';
var imageBackground = new Image();
imageBackground.src = urlBackground;
//imageBackground.crossorigin = "anonymous";
imageBackground.setAttribute('crossorigin', 'anonymous');
$("#target").drawpad();
var canvas = $("#target canvas").get(0);
var contextCanvas = canvas.getContext('2d');
imageBackground.onload = function(){
contextCanvas.drawImage(imageBackground, 0, 0);
$("#clear").trigger("click"); // clear previous drawings when page refreshed
$("#save").trigger("click"); // save the first image (background only)
}
});
body {background-color:rgb(248, 255, 227)}
#target {
width:500px;
height:400px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://cnbilgin.github.io/jquery-drawpad/jquery-drawpad.css" />
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cnbilgin.github.io/jquery-drawpad/jquery-drawpad.js"></script>
</head>
<body>
<button id="undo">Undo</button>
<button id="save">Save</button>
<button id="clear">Clear Saved Picture</button>
<span id="numOfSavedHistory">0</span>
<div id="target" class="drawpad-dashed"></div>
<div id="outputBase64"></div>
</body>
</html>
I have created a simple html using the draggable marker example from here maps. I have adapted it to support IE 11 by adding reference to legacy js, meta tag and using P2D engine in map options. Also added two url parameters for coordinates. It works perfectly in IE11 and it loads and shows pan and zoom buttons in ms-access webbrowser but it keeps static, it's not draggable, but pan and zoom works.
The curious thing is that if I navigate to wego.here.com in the same webbrowser control then the map is draggable. So they're doing something else in the here maps main page that I'm not doing in my script.
I have also tried using Microsoft Web Browser from the activex controls list in access.
I need it to be draggable so I can pick the coordinates after the user changes the marker position.
This is my script:
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Draggable Marker</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-core.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-core-legacy.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-service.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-service-legacy.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-ui.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js" type="text/javascript" charset="utf-8"></script>
<style>
html, body { margin:0px; padding:0px; width: 100%; height: 100%; }
.main { height: 100%; }
</style>
</head>
<body id="markers-on-the-map">
<div class="main" style="width:100%" id="map"></div>
<input type="hidden" id="long" name="long">
<input type="hidden" id="lat" name="lat">
<script>
function addDraggableMarker(map, behavior){
var marker = new H.map.Marker({lat:latitud, lng:longitud}, {volatility: true});
// Ensure that the marker can receive drag events
marker.draggable = true;
map.addObject(marker);
// disable the default draggability of the underlying map
// and calculate the offset between mouse and target's position
// when starting to drag a marker object:
map.addEventListener('dragstart', function(ev) {
var target = ev.target,
pointer = ev.currentPointer;
if (target instanceof H.map.Marker) {
var targetPosition = map.geoToScreen(target.getGeometry());
target['offset'] = new H.math.Point(pointer.viewportX - targetPosition.x, pointer.viewportY - targetPosition.y);
behavior.disable();
}
}, false);
// re-enable the default draggability of the underlying map
// when dragging has completed
map.addEventListener('dragend', function(ev) {
var target = ev.target;
if (target instanceof H.map.Marker) {
$('#long').val(ev.target.b.lng);
$('#lat').val(ev.target.b.lat);
behavior.enable();
}
}, false);
// Listen to the drag event and move the position of the marker
// as necessary
map.addEventListener('drag', function(ev) {
var target = ev.target,
pointer = ev.currentPointer;
if (target instanceof H.map.Marker) {
target.setGeometry(map.screenToGeo(pointer.viewportX - target['offset'].x, pointer.viewportY - target['offset'].y));
}
}, false);
}
/**
* Boilerplate map initialization code starts below:
*/
//Step 1: initialize communication with the platform
// In your own code, replace variable window.apikey with your own apikey
var platform = new H.service.Platform({
apikey: '?????????????????????????????????'
});
var defaultLayers = platform.createDefaultLayers();
//url parameters
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = decodeURIComponent(pair[1]);
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
query_string[pair[0]] = arr;
} else {
query_string[pair[0]].push(decodeURIComponent(pair[1]));
}
}
var latitud=query_string.lat;
var longitud=query_string.long;
//Step 2: initialize a map - this map is centered over Boston
var map = new H.Map(document.getElementById('map'),
defaultLayers.raster.normal.map, {
center: {lat:latitud, lng:longitud},
engineType: H.map.render.RenderEngine.EngineType.P2D,
zoom: 12,
pixelRatio: window.devicePixelRatio || 1
});
// add a resize listener to make sure that the map occupies the whole container
//window.addEventListener('resize', () => map.getViewPort().resize());
window.addEventListener('resize', function () {map.getViewPort().resize(); });
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
//var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Step 4: Create the default UI:
var ui = H.ui.UI.createDefault(map, defaultLayers, 'en-US');
// Add the click event listener.
addDraggableMarker(map, behavior);
</script>
</body>
</html>```
Check please on this static page
: your code works for my IE11
I am trying to create a popup window in a map. I have tree layers in my program; the first two layers are working; the third layer where I have template is defined doesn't work, though. In the console I get following errors:
Error: Unable to draw graphic (null): Unable to complete operation.
...usePost,v=h.crossOrigin):A=!!h);g=e.mixin({},g);g._ssl&&(g.url=g.url.replace(/^h...
I tried to solve this problem, by adding time between the layers. It didn't work.
Below is my code. Please let me know if I am making any mistake. Thanks!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!--The viewport meta tag is used to improve the presentation and behavior of the samples
on iOS devices-->
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title> Trees Location</title>
<link rel="stylesheet" href="http://js.arcgis.com/3.11/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="http://js.arcgis.com/3.11/esri/css/esri.css">
<script src="http://js.arcgis.com/3.11/"></script>
<script>
var map;
require(["esri/config", "esri/map","esri/dijit/Popup",
"dojo/dom-construct",
"esri/dijit/PopupTemplate",
"esri/layers/FeatureLayer",
"esri/symbols/SimpleMarkerSymbol",
"esri/tasks/GeometryService",
"esri/layers/ArcGISDynamicMapServiceLayer",
"esri/layers/ArcGISTiledMapServiceLayer",
"esri/Color",
"dojo/domReady!"],
function (esriConfig, Map,Popup,domConstruct, PopupTemplate, FeatureLayer,SimpleMarkerSymbol, GeometryService, ArcGISDynamicMapServiceLayer, ArcGISTiledMapServiceLayer, Color ) {
esriConfig.defaults.geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");
var popupOptions = {
markerSymbol: new SimpleMarkerSymbol("circle", 32, null,
new Color([0, 0, 0, 0.25])),
marginLeft: "20",
marginTop: "20"
};
var popup = new Popup(popupOptions, domConstruct.create("div"));
map = new Map("map", {
center: [-76.756, 40.241],
zoom: 8,
infoWindow: popup
});
var popupTemplate = new PopupTemplate({
title: "{MEMORIAL}",
fieldInfos: [
{
fieldName: "TREEDONOR",
visible: true,
label: "Type"
},
{
fieldName: "TREESPECIES",
visible: true,
label: "Type"
},
{
fieldName: "TREEVARIETY",
visible: true,
label: "Type"
}
]
});
var customBasemap = new ArcGISTiledMapServiceLayer(
"");
map.addLayer(customBasemap);
/* setTimeout(function(){
console.log("pausing a few seconds");
map.addLayer(customBasemap);
},1000); */
var treeLayer = new ArcGISDynamicMapServiceLayer(
"");
// map.addLayer(treeLayer);
setTimeout(function(){
console.log("pausing a few seconds");
map.addLayer(treeLayer);
},1000);
var featureLayer = new FeatureLayer("",
{
infoTemplate: popupTemplate,
outFields: ["TREEDONOR","TREESPECIES","TREEVARIETY", "MEMORIAL"]
});
featureLayer.setDefinitionExpression("MEMORIAL != ''");
map.addLayer(featureLayer);
});
</script>
</head>
<body class="claro">
<div align="center"><strong> Trees Listing </strong><hr>
<i><a target="_self" href="listingtrees.html">Listing</a> | <a target="_self" href="locationtrees.html">Locations </a></i>
</div>
<br>
<div id="map" >
</div>
</body>
</html>
I'm trying to use canvas object on iPad; the user need to draw a free curve with the finger and when he releases the finger the system must close the curve and fill it.
Actually I wrote down the following code but the problem is that it draws but it does not close the path on finger release.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=768px, maximum-scale=1.0" />
<title>sketchpad</title>
<script type="text/javascript" charset="utf-8">
window.addEventListener('load',function(){
// get the canvas element and its context
var canvas = document.getElementById('sketchpad');
var context = canvas.getContext('2d');
var img = new Image();
img.src = 'imp_02.jpg';
context.drawImage(img,0,0,600,600);
var colorPurple = "#cb3594";
context.strokeStyle=colorPurple;
context.lineWidth = 5;
context.fillStyle = "red";
// create a drawer which tracks touch movements
var drawer = {
isDrawing: false,
touchstart: function(coors){
context.beginPath();
context.moveTo(coors.x, coors.y);
this.isDrawing = true;
},
touchmove: function(coors){
if (this.isDrawing) {
context.lineTo(coors.x, coors.y);
context.stroke();
}
},
touchend: function(coors){
if (this.isDrawing) {
context.touchmove(coors);
context.closePath();
this.isDrawing = false;
}
}
};
// create a function to pass touch events and coordinates to drawer
function draw(event){
// get the touch coordinates
var coors = {
x: event.targetTouches[0].pageX,
y: event.targetTouches[0].pageY
};
// pass the coordinates to the appropriate handler
drawer[event.type](coors);
}
// attach the touchstart, touchmove, touchend event listeners.
canvas.addEventListener('touchstart',draw, false);
canvas.addEventListener('touchmove',draw, false);
canvas.addEventListener('touchend',draw, false);
// prevent elastic scrolling
document.body.addEventListener('touchmove',function(event){
event.preventDefault();
},false); // end body.onTouchMove
},false); // end window.onLoad
</script>
<style type="text/css"><!--
body{margin:0;padding:0; font-family:Arial;}
#container{position:relative;}
#sketchpad{ border: 1px solid #000;}
--></style>
</head>
<body>
<div id="container">
<canvas id="sketchpad" width="766" height="944">
Sorry, your browser is not supported.
</canvas>
</div>
</body>
</html>
I don't understand what I missed.
Is there anyone who can help me..... I would appreciate a lot!!
You are fetching the touch end co-ordinates from a wrong array.
event object has one more array called changedTouches where you can find the co-ordinates of the point where the touch ended. These end co-ordinates are not in targetTouches array.
So you need
endCoordX = event.changedTouches[0].pageX;
endCoordY = event.changedTouches[0].pageY;
[modify the above code to fit into your scenario. hope you got the concept.... And seriuosly i too got stuck on the same point in the past and wasted more than an hour to know this fact....]
I am tryign to figure out MVCArray() in google maps v3. I'm using code written by GeoJason as an example. I attached a click event to the markers to get its LatLng postion. It works well but I need to update the MVCArray on the new postion if a marker is dragged to a new location. This part has me stumped.. Anyone know how to do this or can point me to a good resource which explains using MVCArray's? (besides coode docs, its not designed for newbies.. lol)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>GeoJason - Line Length and Polygon Area with Google Maps API v3 Demo</title>
<meta name="keywords" content="" />
<meta name="description" content="Demo of how to get Line Length and Polygon Area with Google Maps API v3" />
<link rel="stylesheet" type="text/css" href="style/default.css" />
<!-- Script -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="js/jquery/jquery-1.4.2.js"></script>
<script type="text/javascript">
var map;
var markerImageDefault = new google.maps.MarkerImage('images/markers/measure-vertex.png',null, null, new google.maps.Point(5,5));
var markerImageHover = new google.maps.MarkerImage('images/markers/measure-vertex-hover.png',null, null, new google.maps.Point(8,8));
var measure = {
ll:new google.maps.MVCArray(),
markers:[],
line:null,
poly:null
};
function Init(){
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 15,
center: new google.maps.LatLng(34.96762, -80.47372),
mapTypeId: google.maps.MapTypeId.ROADMAP,
/* Make the map cursor a crosshair so the user thinks they should click something */
draggableCursor:'crosshair'
});
google.maps.event.addListener(map,'click',function(evt){
measureAdd(evt.latLng);
});
}
function measureAdd(ll){
var marker = new google.maps.Marker({
map:map,
position:ll,
draggable:true,
/* Let the user know they can drag the markers to change shape */
title:'Drag me to change the polygon\'s shape',
icon: markerImageDefault
});
var count = measure.ll.push(ll);
var llIndex = count-1;
if (count>2) /* We've got atleast 3 points, we can measure area */
measureCalc();
/* when dragging stops, and there are more than 2 points in our MVCArray, recalculate length and area measurements */
google.maps.event.addListener(marker,'dragend',function(evt){
if (measure.ll.getLength()>2)
measureCalc();
});
/* when the user 'mouseover's a marker change the image so they know something is different (it's draggable) */
google.maps.event.addListener(marker,'mouseover',function(evt){
marker.setIcon(markerImageHover);
});
google.maps.event.addListener(marker,'mouseout',function(evt){
marker.setIcon(markerImageDefault);
});
// This will allow us to click on the first element to close the polygon
google.maps.event.addListener(marker,'click',function(evt){
//alert(ll + " : " + measure.markers[0].position);
console.log(ll.LatLng);
if(ll == measure.markers[0].position) // Only for the first item
{
alert("You clicked!");
}
});
/* when we drag a marker it resets its respective LatLng value in an MVCArray. Since we're changing a value in an MVCArray, any lines or polygons on the map that reference this MVCArray also change shape ... Perfect! */
google.maps.event.addListener(marker,'drag',function(evt){
measure.ll.setAt(llIndex,evt.latLng);
});
measure.markers.push(marker);
/* find out of the user placed a marker at the end of the polygon. */
if (measure.ll.getLength()>1){
/* We've got 2 points, we can draw a line now */
if (!measure.line){
measure.line = new google.maps.Polyline({
map:map,
clickable:false,
strokeColor:'#FF0000',
strokeOpacity:0.5,
strokeWeight:3,
path:measure.ll
});
}
if (measure.ll.getLength()>2){
/* We've got 3 points, we can draw a polygon now */
if (!measure.poly){
measure.poly = new google.maps.Polygon({
clickable:false,
map:map,
fillOpacity:0.25,
strokeOpacity:0,
paths:measure.ll
});
}
}
}
}
function measureReset(){
/* Remove Polygon */
if (measure.poly) {
measure.poly.setMap(null);
measure.poly = null;
}
/* Remove Line */
if (measure.line) {
measure.line.setMap(null);
measure.line = null;
}
/* remove all LatLngs from the MVCArray */
while (measure.ll.getLength()>0) measure.ll.pop();
/* remove all markers */
for (i=0;i<measure.markers.length;i++){
measure.markers[i].setMap(null);
}
$('#measure span').text('0');
}
function measureCalc(){
var points='';
measure.ll.forEach(function(latLng,ind){
/* build a string of points in (x,y|x,y|x,y|x,y) format */
points+=latLng.lng()+','+latLng.lat()+'|';
});
points=points.slice(0,points.length-1);
/* send a getJSON request to our webserver to get length and area measurements */
$.getJSON('http://api.geojason.info/v1/ws_geo_length_area.php?format=json&in_srid=4326&out_srid=2264&points='+points+'&callback=?',function(data){
if (parseInt(data.total_rows)>0){
/* calculate and inject values in their corresponding "span"s */
//var length = parseFloat(data.rows[0].row.length);
var area = parseFloat(data.rows[0].row.area);
//$('#measure-area-sqft').text(area.toFixed(0));
$('#measure-area-acres').text((area/43560).toFixed(3));
//$('#measure-length-feet').text(length.toFixed(0));
//$('#measure-length-meters').text((length*0.3048).toFixed(1));
}
});
}
</script>
</head>
<body onload="Init();">
<div id="header">Home - Back to Demos</div>
<h2>Line Length and Polygon Area with Google Maps API v3</h2>
<div id="map-canvas"></div>
<div id="content">
<p></p>
<div><input type="button" onclick="measureReset();" value="Clear Measure" /></div>
<div id="measure">
<div>Length: <span id="measure-length-feet">0</span> ft.</div>
<div>Length: <span id="measure-length-meters">0</span> met.</div>
<div>Area: <span id="measure-area-sqft">0</span> ft.²</div>
<div>Area: <span id="measure-area-acres">0</span> ac.</div>
</div>
</div>
</body>
</html>
I guess you need to bind each marker position to a vertex in your polyline (use bindTo method ) - a good example is here
http://gmaps-utility-gis.googlecode.com/svn/trunk/v3test/mvc/poly_bind.html
simple examples here
http://gmaps-samples-v3.googlecode.com/svn/trunk/rectangle-overlay/rectangle-overlay.html
http://gmaps-samples-v3.googlecode.com/svn/trunk/circle-overlay/circle-overlay.html