Google Maps API v3 Geocoding - javascript

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

Related

Drawing a path as an object moves on a map

I have this marker that moves along a google map http://jsfiddle.net/t43kaeyr/ but i need it to draw its path on the map as it moves.
This is the javascript that creates the map
var map,marker;
var startPos = [42.42679066670903, -83.29210638999939];
var speed = 150; // km/h
var delay = 100;
// If you set the delay below 1000ms and you go to another tab,
// the setTimeout function will wait to be the active tab again
// before running the code.
// See documentation :
// https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout#Inactive_tabs
function animateMarker(marker, coords, km_h)
{
var target = 0;
var km_h = km_h || 50;
coords.push([startPos[0], startPos[1]]);
function goToPoint()
{
var lat = marker.position.lat();
var lng = marker.position.lng();
var step = (km_h * 1000 * delay) / 3600000; // in meters
var dest = new google.maps.LatLng(
coords[target][0], coords[target][1]);
var distance =
google.maps.geometry.spherical.computeDistanceBetween(
dest, marker.position); // in meters
var numStep = distance / step;
var i = 0;
var deltaLat = (coords[target][0] - lat) / numStep;
var deltaLng = (coords[target][1] - lng) / numStep;
function moveMarker()
{
lat += deltaLat;
lng += deltaLng;
i += step;
if (i < distance)
{
marker.setPosition(new google.maps.LatLng(lat, lng));
setTimeout(moveMarker, delay);
}
else
{ marker.setPosition(dest);
target++;
if (target == coords.length){ target = 0; }
setTimeout(goToPoint, delay);
}
}
moveMarker();
}
goToPoint();
}
function initialize()
{
var myOptions = {
zoom: 16,
center: new google.maps.LatLng(42.425175091823974, -83.2943058013916),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
marker = new google.maps.Marker({
position: new google.maps.LatLng(startPos[0], startPos[1]),
icon: 'assets/images/c.png',
map: map
});
google.maps.event.addListenerOnce(map, 'idle', function()
{
animateMarker(marker, [
// The coordinates of each point you want the marker to go to.
// You don't need to specify the starting position again.
[42.42666395645802, -83.29694509506226],
[42.42300508749226, -83.29679489135742],
[42.42304468678425, -83.29434871673584],
[42.424882066428424, -83.2944130897522],
[42.42495334300206, -83.29203128814697]
], speed);
});
}
initialize();
I tried drawing the path and the path is drawn correctly but the object does not move any more. This is the code
var map,marker;
var startPos = [42.42679066670903, -83.29210638999939];
var speed = 150; // km/h
var delay = 100;
// If you set the delay below 1000ms and you go to another tab,
// the setTimeout function will wait to be the active tab again
// before running the code.
// See documentation :
// https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout#Inactive_tabs
function animateMarker(marker, coords, km_h)
{
var target = 0;
var km_h = km_h || 50;
coords.push([startPos[0], startPos[1]]);
function goToPoint()
{
var lat = marker.position.lat();
var lng = marker.position.lng();
var step = (km_h * 1000 * delay) / 3600000; // in meters
var dest = new google.maps.LatLng(
coords[target][0], coords[target][1]);
var distance =
google.maps.geometry.spherical.computeDistanceBetween(
dest, marker.position); // in meters
var numStep = distance / step;
var i = 0;
var deltaLat = (coords[target][0] - lat) / numStep;
var deltaLng = (coords[target][1] - lng) / numStep;
function moveMarker()
{
lat += deltaLat;
lng += deltaLng;
i += step;
if (i < distance)
{
marker.setPosition(new google.maps.LatLng(lat, lng));
setTimeout(moveMarker, delay);
}
else
{ marker.setPosition(dest);
target++;
if (target == coords.length){ target = 0; }
setTimeout(goToPoint, delay);
}
}
moveMarker();
}
goToPoint();
}
function initialize()
{
var myOptions = {
zoom: 16,
center: new google.maps.LatLng(42.425175091823974, -83.2943058013916),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
marker = new google.maps.Marker({
position: new google.maps.LatLng(startPos[0], startPos[1]),
icon: 'assets/images/c.png',
map: map
});
var flightPlanCoordinates = [
{lat: 42.42666395645802, lng: -83.29694509506226},
{lat: 42.42300508749226, lng: -83.29679489135742},
{lat: 42.42304468678425, lng: -83.29434871673584},
{lat: 42.424882066428424, lng: -83.2944130897522},
{lat: 42.42495334300206, lng: -83.29203128814697}
];
google.maps.event.addListenerOnce(map, 'idle', function()
{
animateMarker(marker, [
// The coordinates of each point you want the marker to go to.
// You don't need to specify the starting position again.
flightPlanCoordinates
], speed);
});
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
initialize();
How can i make the marker to draw its path as it moves on the map?.
Maybe you want create a Polyline with a Line with multiple points, which represents each position of the marker:
provide a global variable:
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: 0, lng: -180},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var polylineCoords = [];
var path = new google.maps.Polyline({
path: polylineCoords,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
path.setMap(map);
//To add a Point on the polyline call
function addCoord(lat, lng) {
var point = new google.maps.LatLng(lat, lng);
var coords = path.getPath();
coords.push(point);
}
JSFiddle

Circle fade out over time on Google Map [duplicate]

This question already has an answer here:
How do I fade out a circle in a Google Map, x seconds after I've added it to the map?
(1 answer)
Closed 8 years ago.
I am attempting to fade circles out with a setInterval on fillOpacity. However a console log shows the opacity changing but the appearance of the circle does not seem to change. Is there a different set function required to do this?
http://jsfiddle.net/faaxeskg/5/
setInterval(function() {
marker.fillOpacity -= .01;
console.log(marker.fillOpacity);
}, 200);
code snippet:
var map = null;
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882, 131.044922)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Add 500 markers to the map at random locations
var southWest = new google.maps.LatLng(-31.203405, 125.244141);
var northEast = new google.maps.LatLng(-25.363882, 131.044922);
var bounds = new google.maps.LatLngBounds(southWest, northEast);
map.fitBounds(bounds);
var lngSpan = northEast.lng() - southWest.lng();
var latSpan = northEast.lat() - southWest.lat();
setInterval(function() {
var position = new google.maps.LatLng(
southWest.lat() + latSpan * Math.random(),
southWest.lng() + lngSpan * Math.random());
var populationOptions = {
strokeOpacity: 0,
fillColor: '#FF0000',
fillOpacity: 0.65,
map: map,
center: position,
radius: 40000
};
var marker = new google.maps.Circle(populationOptions);
setInterval(function() {
marker.fillOpacity -= .01;
console.log(marker.fillOpacity);
}, 200);
setTimeout(function() {
marker.setMap(null);
delete marker;
}, 30000);
}, 2000);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=geometry"></script>
<div id="map-canvas" style="float:left;width:100%;height:100%;"></div>
You need to associate the "opacity change" to the marker, you can do that with function closure (a createCircleMarker function).
Don't use undocumented properties. Use the documented methods.
marker.set("fillOpacity, marker.get("fillOpacity")-0.01);
working code snippet:
var map = null;
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882, 131.044922)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Add 500 markers to the map at random locations
var southWest = new google.maps.LatLng(-31.203405, 125.244141);
var northEast = new google.maps.LatLng(-25.363882, 131.044922);
var bounds = new google.maps.LatLngBounds(southWest, northEast);
map.fitBounds(bounds);
var lngSpan = northEast.lng() - southWest.lng();
var latSpan = northEast.lat() - southWest.lat();
setInterval(function() {
var position = new google.maps.LatLng(
southWest.lat() + latSpan * Math.random(),
southWest.lng() + lngSpan * Math.random());
var populationOptions = {
strokeOpacity: 0,
fillColor: '#FF0000',
fillOpacity: 0.65,
map: map,
center: position,
radius: 40000
};
createCircleMarker(populationOptions);
}, 2000);
}
function createCircleMarker(populationOptions) {
var marker = new google.maps.Circle(populationOptions);
setInterval(function() {
marker.set("fillOpacity",marker.get("fillOpacity")-0.05);
console.log(marker.fillOpacity);
}, 200);
setTimeout(function() {
marker.setMap(null);
delete marker;
}, 30000);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=geometry"></script>
<div id="map-canvas" style="float:left;width:100%;height:100%;"></div>

Toggling Google map circle Hide and UnHide

I want to hide and show Google map circle. Hope the API has provided any simple method but I am unable to figure it out.
And can anyone let me know how to place the circle to left corner of the map?
Waiting for your help, here is my code:
/**
* A distance widget that will display a circle that can be resized and will
* provide the radius in km.
*
* #param {google.maps.Map} map The map to attach to.
*
* #constructor
*/
function DistanceWidget(map) {
this.set('map', map);
this.set('position', map.getCenter());
var marker = new google.maps.Marker({
draggable: true,
title: 'Move me!'
});
// Bind the marker map property to the DistanceWidget map property
marker.bindTo('map', this);
// Bind the marker position property to the DistanceWidget position
// property
marker.bindTo('position', this);
// Create a new radius widget
var radiusWidget = new RadiusWidget();
// Bind the radiusWidget map to the DistanceWidget map
radiusWidget.bindTo('map', this);
// Bind the radiusWidget center to the DistanceWidget position
radiusWidget.bindTo('center', this, 'position');
// Bind to the radiusWidgets' distance property
this.bindTo('distance', radiusWidget);
// Bind to the radiusWidgets' bounds property
this.bindTo('bounds', radiusWidget);
}
DistanceWidget.prototype = new google.maps.MVCObject();
/**
* A radius widget that add a circle to a map and centers on a marker.
*
* #constructor
*/
function RadiusWidget() {
var circle = new google.maps.Circle({
strokeWeight: 2
});
// Set the distance property value, default to 50km.
this.set('distance', 50);
// Bind the RadiusWidget bounds property to the circle bounds property.
this.bindTo('bounds', circle);
// Bind the circle center to the RadiusWidget center property
circle.bindTo('center', this);
// Bind the circle map to the RadiusWidget map
circle.bindTo('map', this);
// Bind the circle radius property to the RadiusWidget radius property
circle.bindTo('radius', this);
// Add the sizer marker
this.addSizer_();
}
RadiusWidget.prototype = new google.maps.MVCObject();
/**
* Update the radius when the distance has changed.
*/
RadiusWidget.prototype.distance_changed = function () {
this.set('radius', this.get('distance') * 1000);
};
/**
* Add the sizer marker to the map.
*
* #private
*/
RadiusWidget.prototype.addSizer_ = function () {
var sizer = new google.maps.Marker({
draggable: true,
title: 'Drag me!'
});
sizer.bindTo('map', this);
sizer.bindTo('position', this, 'sizer_position');
var me = this;
google.maps.event.addListener(sizer, 'drag', function () {
// Set the circle distance (radius)
me.setDistance();
});
};
/**
* Update the center of the circle and position the sizer back on the line.
*
* Position is bound to the DistanceWidget so this is expected to change when
* the position of the distance widget is changed.
*/
RadiusWidget.prototype.center_changed = function () {
var bounds = this.get('bounds');
// Bounds might not always be set so check that it exists first.
if (bounds) {
var lng = bounds.getNorthEast().lng();
// Put the sizer at center, right on the circle.
var position = new google.maps.LatLng(this.get('center').lat(), lng);
this.set('sizer_position', position);
}
};
/**
* Calculates the distance between two latlng points in km.
* #see http://www.movable-type.co.uk/scripts/latlong.html
*
* #param {google.maps.LatLng} p1 The first lat lng point.
* #param {google.maps.LatLng} p2 The second lat lng point.
* #return {number} The distance between the two points in km.
* #private
*/
RadiusWidget.prototype.distanceBetweenPoints_ = function (p1, p2) {
if (!p1 || !p2) {
return 0;
}
var R = 6371; // Radius of the Earth in km
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;
};
/**
* Set the distance of the circle based on the position of the sizer.
*/
RadiusWidget.prototype.setDistance = function () {
// As the sizer is being dragged, its position changes. Because the
// RadiusWidget's sizer_position is bound to the sizer's position, it will
// change as well.
var pos = this.get('sizer_position');
var center = this.get('center');
var distance = this.distanceBetweenPoints_(center, pos);
// Set the distance property for any objects that are bound to it
this.set('distance', distance);
};
function init() {
var mapDiv = document.getElementById('map-canvas');
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(37.790234970864, -122.39031314844),
zoom: 8,
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);
});
}
function displayInfo(widget) {
var info = document.getElementById('info');
info.innerHTML = 'Position: ' + widget.get('position') + ', distance: ' + widget.get('distance');
}
google.maps.event.addDomListener(window, 'load', init);
Changed this code (made "map" and "distanceWidget" global):
var map = null;
var distanceWidget = null;
function init() {
var mapDiv = document.getElementById('map-canvas');
map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(37.790234970864, -122.39031314844),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
distanceWidget = new DistanceWidget(map);
google.maps.event.addListener(distanceWidget, 'distance_changed', function () {
displayInfo(distanceWidget);
});
google.maps.event.addListener(distanceWidget, 'position_changed', function () {
displayInfo(distanceWidget);
});
}
function displayInfo(widget) {
var info = document.getElementById('info');
info.innerHTML = 'Position: ' + widget.get('position') + ', distance: ' + widget.get('distance');
}
Added this to the HTML, hides and shows the distanceWidget:
<button onclick="distanceWidget.set('map',null);" >Hide</button>
<button onclick="distanceWidget.set('map',map);">Show</button>
<div id="info"></div>
<div id="map-canvas"></div>
working fiddle

How can I create a draggable rectangle in map api v3

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

How to display a label next to a Marker for Google Maps?

I would like to display a text label next to the markers on google maps. I've used Virtual Earth before and I'm just starting to use Google Maps. I tried setting the Title property but that only changes the roll over text.
Is there a way to display a small line of text underneath a marker that will stay there as the user zooms, pans and uses the map?
If you just want to show label below the marker, then you can extend google maps Marker to add a setter method for label and you can define the label object by extending google maps overlayView like this..
Demo: jsFiddle
<script type="text/javascript">
var point = { lat: 22.5667, lng: 88.3667 };
var markerSize = { x: 22, y: 40 };
google.maps.Marker.prototype.setLabel = function(label){
this.label = new MarkerLabel({
map: this.map,
marker: this,
text: label
});
this.label.bindTo('position', this, 'position');
};
var MarkerLabel = function(options) {
this.setValues(options);
this.span = document.createElement('span');
this.span.className = 'map-marker-label';
};
MarkerLabel.prototype = $.extend(new google.maps.OverlayView(), {
onAdd: function() {
this.getPanes().overlayImage.appendChild(this.span);
var self = this;
this.listeners = [
google.maps.event.addListener(this, 'position_changed', function() { self.draw(); })];
},
draw: function() {
var text = String(this.get('text'));
var position = this.getProjection().fromLatLngToDivPixel(this.get('position'));
this.span.innerHTML = text;
this.span.style.left = (position.x - (markerSize.x / 2)) - (text.length * 3) + 10 + 'px';
this.span.style.top = (position.y - markerSize.y + 40) + 'px';
}
});
function initialize(){
var myLatLng = new google.maps.LatLng(point.lat, point.lng);
var gmap = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
map: gmap,
position: myLatLng,
label: 'Hello World!',
draggable: true
});
}
</script>
<style>
.map-marker-label{
position: absolute;
color: blue;
font-size: 16px;
font-weight: bold;
}
</style>
This will work.

Categories

Resources