Related
I am encountering an issue when drawing polygons, point, and line features on a map using the Leaflet.js library.
The polygon is correctly displayed on the map, but the moment I try to draw a point ** or **line, they **disappear **immediately after releasing the mouse click. I need assistance to correct this issue and make the drawing of points and lines on the map functional.
var map = L.map("leaflet-map", {
center: [37.7749, -122.4194],
zoom: 8,
});
let osm = L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}", {
foo: "bar",
attribution: "© OpenStreetMap contributors",
});
osm.addTo(map);
var CyclOSM = L.tileLayer(
"https://{s}.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png",
{
attribution: "CyclOSM | Map data: © OpenStreetMap contributors",
}
);
CyclOSM.addTo(map);
var Esri_WorldImagery = L.tileLayer(
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
{
attribution:
"Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community",
}
).addTo(map);
let baseLayers = {
"Esri World Imagery": Esri_WorldImagery,
"Open Street Map": osm,
"Cycl OSM": CyclOSM,
};
//Creates three feature groups for points, polygons, and lines on the map
var pointLayer = L.featureGroup().addTo(map);
var polygonsLayer = L.featureGroup().addTo(map);
var lineLayer = L.featureGroup().addTo(map);
var polygon;
var point;
var line;
var allLayers = L.featureGroup([pointLayer, polygonsLayer, lineLayer]).addTo(
map
);
//Add new shapes drawn on the map to the appropriate feature group
map.on("draw:created", function (e) {
var type = e.layerType,
layer = e.layer;
if (type === "point") {
point = layer;
point.addTo(pointLayer);
point.addTo(map);
} else if (type === "polygon") {
polygon = layer;
polygon.addTo(polygonsLayer);
polygonsLayer.addTo(map);
} else if (type === "line") {
line = layer;
line.addTo(lineLayer);
lineLayer.addTo(map);
}
});
var drawControl = new L.Control.Draw({
draw: {
marker: true,
polyline: true,
polygon: true,
rectangle: true,
circle: true,
},
}).addTo(map);
You define 5 types of shapes:
marker, polyline, polygon, rectangle, and circle
but in the feature group, you only catch polyline
To catch makers, you need to change this block:
if (type === "point") {
point = layer;
point.addTo(pointLayer);
point.addTo(map);
to:
if (type === "marker") {
point = layer;
point.addTo(pointLayer);
pointLayer.addTo(map); //add the layer to the map
same for polyline, rectangle and circle.
You can have a look at the Leaflet Draw documentation, you can catch all shapes by not checking for type and directly adding the e.layer from the draw event to the map.
On the map, I have an added layer with polygons and one marker on another layer. When I click anywhere, the marker moves to that location and the polygon is selected. The marker has the ability to drag across the map, but just when I drag it, the polygon selection does not appear. How to do this?
var osm = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
});
var map = new L.Map('map', {
'center': [51, 17],
'zoom': 6,
'layers': [osm],
});
var selected;
var marker
marker = L.marker([51, 17], {
draggable: true
}).addTo(map);
var geoJsonLayer2
geoJsonLayer2 = L.geoJson( polygons ,{
style: {
fillColor: "#1ED100",
color: "orange",
fillOpacity: 0.0,
opacity: 0.0,
},
})
.on('click', function (e) {
// Check for selected
if (selected) {
// Reset selected to default style
e.target.resetStyle(selected)
}
// Assign new selected
selected = e.layer
// Bring selected to front
selected.bringToFront()
// Style selected
selected.setStyle({
'color': 'red',
'opacity': 1,
})
})
.addTo(map);
marker.on('dragend', function (e, feature) {
updateLatLng(marker.getLatLng().lat, marker.getLatLng().lng);
});
map.on('click', function (e) {
marker.setLatLng(e.latlng);
updateLatLng(marker.getLatLng().lat, marker.getLatLng().lng);
});
function updateLatLng(lat, lng, reverse) {
if (reverse) {
marker.setLatLng([lat, lng]);
map.panTo([lat, lng]);
} else {
document.getElementById('lat').value = marker.getLatLng().lat.toFixed(10);
document.getElementById('long').value = marker.getLatLng().lng.toFixed(10);
map.panTo([lat, lng]);
document.getElementById("lat").value = lat.toFixed(10);
document.getElementById("long").value = lng.toFixed(10);
}
}
view after clicking on the polygon
view after shifting the marker
This question already has answers here:
How to get point coordinates of a modified drawingManager shape? GoogleMaps API v3
(2 answers)
Closed 9 years ago.
I have an example how to write polygon on google map:
http://jsbin.com/quzed/1/edit
So here is the code:
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);
How i can see what are coordinates from drawen polygon, and how to save it (etc. mysql) also how to write polygon if you know coordinates ?
Can sombody help me? I lose in this code? Where is coordinates from user action (user drawing polygon)?
ETC. if I have 3 coordinates (44.5, 55.6) (45.7, 56.87) (46.7, 46.8) how I can draw it here?
And if I draw some polygon on example, how I can see coordinates for polygon?
Look at the example on google's site.
Given you already have that polygon, you can get it's path coordinates with the getPath method.
console.log(bermudaTriangle.getPath() );
There's also a setPath method which would accept an array of coordinates (or an MVCArray for that matter).
Polygons can also have interior rings (as in a donut), but you should get accustomed to simple convex polygons before trying that.
Regarding the question as to "how to save a drawn polygon", Google Maps API provides static functions to encode polygon and polyline paths so you can persist the objects as text.
There are other libraries such as Wicket that can take a Google Maps Object and encode it with a standard WKT format, that is natively understood by geometrical enabled databases.
How can I create a draggable rectangle in map api v3 as you see in my code my rectangle is draggable onclick on the marker center i wont to drag my rectangle on click of all the rectangle thx for help :
(function()
{
window.onload = function()
{
var path;
var counter = 0;
// Creating a map
var options =
{
zoom: 11,
center: new google.maps.LatLng(49.2541, -123.072),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('mapDiv'), options);
};// end window.onload
})();// end anonymous function
//-------------------------createRectangle BEGINS---------------------------
/**
* Creates the rectangle
*/
function createRectangle()
{
// make the center marker
try
{
markerCenter.setMap(null);
markerSouthWest.setMap(null);
markerNorthEast.setMap(null);
rectangle.setMap(null);
fusionLayer.setMap(null);
}
catch(err){}
centerPositionSave = map.getCenter();
latLngSouthWest = map.getCenter().DestinationPoint(225,4200); // 225 degrees, 1200 meters
latLngNorthEast = map.getCenter().DestinationPoint(45,4200); // 45 degrees, 1200 meters
bounds = new google.maps.LatLngBounds(latLngSouthWest,latLngNorthEast);
rectangle = new google.maps.Rectangle
(
{
strokeWeight: 2,
bounds:bounds,
map:map,
}
); // end rectangle
markerSouthWest = new google.maps.Marker(
{
draggable: true,
title: 'south west',
icon:polyEditSquare,
raiseOnDrag:false,
position: latLngSouthWest,
map: map
}); // end markerSouthWest
google.maps.event.addListener(markerSouthWest,'drag',markerSouthWestDrag);
markerNorthEast = new google.maps.Marker(
{
draggable: true,
title: 'north east',
icon:polyEditSquare,
raiseOnDrag:false,
position: latLngNorthEast,
map: map
}); // end markerNorthEast
google.maps.event.addListener(markerNorthEast,'drag',markerNorthEastDrag);
markerCenter = new google.maps.Marker(
{
draggable: true,
title: 'center',
icon: new google.maps.MarkerImage("icons/move.png"),
raiseOnDrag:false,
position: map.getCenter(),
map: map
});// end markerCenter
markerClose = new google.maps.Marker(
{
draggable: false,
title: 'Fermer',
icon: new google.maps.MarkerImage("icons/x.png", new google.maps.Size(16,16), new google.maps.Point(0,0), new google.maps.Point(8,8)),
raiseOnDrag:false,
position: new google.maps.LatLng(latLngNorthEast.lat(), latLngSouthWest.lng()),
map: map
});// end markerClose
google.maps.event.addListener(markerCenter, 'drag', markerCenterDrag);
google.maps.event.addListener(markerClose,'click',markerCenterDoubleClick);
}//end of createRectangle
//new google.maps.LatLng(latLngSouthWest.lat(),latLngNorthEast.lng())///////////////////////////::::::
//------------------------------createRectangle ENDS------------------------
//-------------------------markerCenterDoubleClick BEGINS---------------------------
/**
* Handles the markerCenter doubleclick event. Removes the rectangle.
*/
function markerCenterDoubleClick(e)
{
rectangle.setMap(null);
markerCenter.setMap(null);
markerSouthWest.setMap(null);
markerNorthEast.setMap(null);
markerClose.setMap(null);
}//end of markerCenterDoubleClick
//------------------------------markerCenterDoubleClick ENDS------------------------
//-------------------------markerCenterDrag BEGINS---------------------------
/**
* Handles the center marker drag event. We want the southwest and northwest markers to update accordingly
*/
function markerCenterDrag(e)
{
var southWest = markerSouthWest.getPosition();
var northEast = markerNorthEast.getPosition();
centerPositionNew = markerCenter.getPosition();
var distance = google.maps.geometry.spherical.computeDistanceBetween(centerPositionSave,centerPositionNew);
var headingNew = google.maps.geometry.spherical.computeHeading(centerPositionSave,centerPositionNew);
var newSouthWest = google.maps.geometry.spherical.computeOffset(southWest,distance,headingNew);
var newNorthEast = google.maps.geometry.spherical.computeOffset(northEast,distance,headingNew);
markerSouthWest.setPosition(newSouthWest);
markerNorthEast.setPosition(newNorthEast);
bounds = new google.maps.LatLngBounds(newSouthWest,newNorthEast);
rectangle.setBounds(bounds);
centerPositionSave = centerPositionNew;
markerClose.setPosition(new google.maps.LatLng(newNorthEast.lat(), newSouthWest.lng()));
}//end of markerCenterDrag
//------------------------------markerCenterDrag ENDS------------------------
//-------------------------markerSouthWestDrag BEGINS---------------------------
/**
* Handles the southwest marker drag event. We want the rectangle to update accordingly.
*/
function markerSouthWestDrag(e)
{
latLngSouthWest = markerSouthWest.getPosition();
latLngNorthEast = markerNorthEast.getPosition();
bounds = new google.maps.LatLngBounds(latLngSouthWest,latLngNorthEast);
rectangle.setBounds(bounds);
center = bounds.getCenter();
markerCenter.setPosition(center);
centerPositionSave = center;
markerClose.setPosition(new google.maps.LatLng(latLngNorthEast.lat(), latLngSouthWest.lng()));
}//end of markerSouthWestDrag
//------------------------------markerNorthEastDrag ENDS------------------------
/**
* Handles the southwest marker drag event. We want the rectangle to update accordingly.
*/
function markerNorthEastDrag(e)
{
latLngSouthWest = markerSouthWest.getPosition();
latLngNorthEast = markerNorthEast.getPosition();
bounds = new google.maps.LatLngBounds(latLngSouthWest,latLngNorthEast);
rectangle.setBounds(bounds);
center = bounds.getCenter();
markerCenter.setPosition(center);
centerPositionSave = center;
markerClose.setPosition(new google.maps.LatLng(latLngNorthEast.lat(), latLngSouthWest.lng()));
}//end of markerNorthEastDrag
//------------------------------markerNorthEastDrag ENDS------------------------
//-------------------------fusionCommunityCentres BEGINS---------------------------
/**
* Puts the community centres Fusion Table on the map
*/
function fusionCommunityCentres()
{
tableId = 1067437;
southWest = markerSouthWest.getPosition().toString();
northEast = markerNorthEast.getPosition().toString();
query = "SELECT * FROM " + tableId + " WHERE ST_INTERSECTS(geometry, RECTANGLE(LATLNG" +
southWest + ", LATLNG" + northEast + "))";
$("#queryOutput").html("Query sent to Fusion Tables:<br>" + query);
fusionLayer = new google.maps.FusionTablesLayer(tableId,
{
query: query,
map:map
});
//layer.setMap(map);
}//end of fusionCommunityCentres
//------------------------------fusionCommunityCentres ENDS------------------------
Here I drag a single rectangle.
Since there's no drag event for Rectangles, I assign a marker to its center, and let its drag event control the rect movement.
The code can be extended, like adding a marker directly to the Rectangle object, or even subclass it. You decide.
You can set in oprtions rectangle to be draggable.
Try:
var rectangle = new google.maps.Rectangle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
draggable:true,//<-----------Here set draggable option
bounds: new google.maps.LatLngBounds(
new google.maps.LatLng(33.671068, -116.25128),
new google.maps.LatLng(33.785282, -116.133942))
});
DEMO
your help would be much appreciated with the following. I am using the JS code below to display a Google Map with a re-sizable circle overlay to output a centre point co-ordinate, radius and bounding box:
function DistanceWidget(map) {
this.set('map', map);
this.set('position', map.getCenter());
var marker = new google.maps.Marker({
draggable: true,
title: 'Drag to set centre',
icon: 'images/mapicon3.png'
});
marker.bindTo('map', this);
marker.bindTo('position', this);
var radiusWidget = new RadiusWidget();
radiusWidget.bindTo('map', this);
radiusWidget.bindTo('center', this, 'position');
this.bindTo('distance', radiusWidget);
this.bindTo('bounds', radiusWidget);
}
DistanceWidget.prototype = new google.maps.MVCObject();
function RadiusWidget() {
var circle = new google.maps.Circle({
fillColor: '#efefef',
fillOpacity: 0.5,
strokeColor: '#000',
strokeOpacity: 1.0,
strokeWeight: 2
});
this.set('distance', 5);
this.bindTo('bounds', circle);
circle.bindTo('center', this);
circle.bindTo('map', this);
circle.bindTo('radius', this);
this.addSizer_();
}
RadiusWidget.prototype = new google.maps.MVCObject();
RadiusWidget.prototype.distance_changed = function() {
this.set('radius', this.get('distance') * 1000);
};
RadiusWidget.prototype.addSizer_ = function() {
var sizer = new google.maps.Marker({
draggable: true,
title: 'Drag to expand search area',
icon: 'images/mapicon2.png'
});
sizer.bindTo('map', this);
sizer.bindTo('position', this, 'sizer_position');
var me = this;
google.maps.event.addListener(sizer, 'drag', function() {
me.setDistance();
});
};
RadiusWidget.prototype.center_changed = function() {
var bounds = this.get('bounds');
if (bounds) {
var lng = bounds.getNorthEast().lng();
var position = new google.maps.LatLng(this.get('center').lat(), lng);
this.set('sizer_position', position);
}
};
RadiusWidget.prototype.distanceBetweenPoints_ = function(p1, p2) {
if (!p1 || !p2) {
return 0;
}
var R = 6371;
var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
};
RadiusWidget.prototype.setDistance = function() {
var pos = this.get('sizer_position');
var center = this.get('center');
var distance = this.distanceBetweenPoints_(center, pos);
var distance = Math.round(distance*100)/100
this.set('distance', distance);
};
function init() {
var mapDiv = document.getElementById('map-canvas');
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(geoip_latitude(), geoip_longitude()), zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var distanceWidget = new DistanceWidget(map);
google.maps.event.addListener(distanceWidget, 'distance_changed', function() {
displayInfo(distanceWidget);
});
google.maps.event.addListener(distanceWidget, 'position_changed', function() {
displayInfo(distanceWidget);
});
mapDiv.style.width = (viewportwidth)+"px";
mapDiv.style.height = (viewportheight)+"px";
}
function displayInfo(widget) {
var info = document.getElementById('info');
info.innerHTML = '<form action="/search" method="post"><input type="hidden" name="position" value="' + widget.get('position') + '" /><input type="hidden" name="distance" value="' + widget.get('distance') + '" /><input type="hidden" name="bounds" value="' + widget.get('bounds') + '" /><input type="submit" value="Submit" /></form>';
}
google.maps.event.addDomListener(window, 'load', init);
This works great, but what I can't figure out is how to add geocoding to this, so that a place name could be entered (POSTed via a form), geocoded using Google Maps API and set as the centre point in the above script, without breaking the current functionality.
As requested, there is a jsFiddle for the above here. You will see that the user can drag the markers to output position, distance and bounds; however what I want to add is the ability to enter a location in the form, which on submit is geocoded, with the resulting co-ordinates being used to reposition the centre marker.
Any help much appreciated, thanks.
Here is the JSFiddle Demo: and type in zipcode (30084) to test it:
Here is the initial markup of the HTML:
<div id="map-canvas"></div>
<div id="info">
</div>
<div id='geocode'>
<input name="q" type="text" id="q" /><br />
<input type="submit" value="Submit" id="geosubmit" />
</div>
Here is how you can get the Geocode information based on the input, and within the callback function of your geocode you can set the center of your DistanceWidget. The responseResult would give you lat by calling responses[0].geometry.location.lat() and lng by responses[0].geometry.location.lng():
function init() {
var mapDiv = document.getElementById('map-canvas');
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(51.5001524, -0.1262362),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var distanceWidget = new DistanceWidget(map);
//Geocoder input section and logic
var mySubmit = document.getElementById('geosubmit');
var myGeoInfo = document.getElementById('q');
mySubmit.onclick = function() {
geocoder.geocode({
address: myGeoInfo.value
}, function(responses) {
if (responses && responses.length > 0) {
var newMarkerPos = new google.maps.LatLng(responses[0].geometry.location.lat(), responses[0].geometry.location.lng());
distanceWidget.set('position', newMarkerPos); //sets the new position of marker
distanceWidget.map.setCenter(newMarkerPos); //sets map's center
} else {
//response failed output error message
alert('error getting geocode');
}
});
}
google.maps.event.addListener(distanceWidget, 'distance_changed', function() {
displayInfo(distanceWidget);
});
google.maps.event.addListener(distanceWidget, 'position_changed', function() {
displayInfo(distanceWidget);
});
mapDiv.style.width = "500px";
mapDiv.style.height = "300px";
}
Update. Please check the JSFiddle demo and type in zipcode (30084) to test it:
To set your current RadiusWidget and google map marker here is the modified code. You don't need to modify the prototype of your current widget to complicate things. You can just call the MVCObject's set option and access the map by using the instantiated distancewidget:
geocoder.geocode({
address: myGeoInfo.value
}, function(responses) {
if (responses && responses.length > 0) {
var newMarkerPos = new google.maps.LatLng(responses[0].geometry.location.lat(), responses[0].geometry.location.lng());
distanceWidget.set('position', newMarkerPos); //sets the new position of marker
distanceWidget.map.setCenter(newMarkerPos); //sets map's center
} else {
//response failed output error message
alert('error getting geocode');
}
});
If you change your marker in DistanceWidget to be a instance variable instead, and create a setPosition() method operating on that marker I think you should be able to do what you want;
function DistanceWidget(map) {
this.set('map', map);
this.set('position', map.getCenter());
this.marker = new google.maps.Marker({
draggable: true,
title: 'Drag to set centre',
icon: 'images/mapicon3.png'
});
this.marker.bindTo('map', this);
this.marker.bindTo('position', this);
var radiusWidget = new RadiusWidget();
radiusWidget.bindTo('map', this);
radiusWidget.bindTo('center', this, 'position');
this.bindTo('distance', radiusWidget);
this.bindTo('bounds', radiusWidget);
}
DistanceWidget.prototype = new google.maps.MVCObject();
/* Add the `setMarkerPosition` method to this class */
DistanceWidget.prototype.setMarkerPosition = function(position) {
this.marker.setPosition(position);
}
And your init()-function becomes;
function init() {
var mapDiv = document.getElementById('map-canvas');
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(geoip_latitude(), geoip_longitude()), zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var distanceWidget = new DistanceWidget(map);
/* Set up geo-functionality */
var geo = new google.maps.Geocoder();
geo.geocode({address: 'Piccadilly Circus, London'}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
distanceWidget.setMarkerPosition(results[0].geometry.location);
map.setCenter(results[0].geometry.location);
}
});
...
DISCLAIMER: This is just from the top of my head, not tested plus I've never worked with these classes.
There is a tutorial here that shows how to get geocoding and reverse geocoding working with Google Maps v3 and Jquery