Javascript : get mid point (centroid) between Lat Long in Google Maps - javascript

I have a google maps based program that can calculate the area based on user input. Here the Demo JSFiddle
The HTML should be like this
<div class="google-maps" id="map" style="height: 400px; position: relative; border: 1px solid #CCC;"></div>
<p>Length (red line):
<span id="span-length">0</span> mt - Area (grey area): <span id="span-area">0</span> mt2</p>
And the Javascript
var map;
// Create a meausure object to store our markers, MVCArrays, lines and polygons
var measure = {
mvcLine: new google.maps.MVCArray(),
mvcPolygon: new google.maps.MVCArray(),
mvcMarkers: new google.maps.MVCArray(),
line: null,
polygon: null
};
// When the document is ready, create the map and handle clicks on it
jQuery(document).ready(function() {
map = new google.maps.Map(document.getElementById("map"), {
zoom: 15,
center: new google.maps.LatLng(39.57592, -105.01476),
mapTypeId: google.maps.MapTypeId.ROADMAP,
draggableCursor: "crosshair" // Make the map cursor a crosshair so the user thinks they should click something
});
google.maps.event.addListener(map, "click", function(evt) {
// When the map is clicked, pass the LatLng obect to the measureAdd function
measureAdd(evt.latLng);
});
});
function measureAdd(latLng) {
// Add a draggable marker to the map where the user clicked
var marker = new google.maps.Marker({
map: map,
position: latLng,
draggable: true,
raiseOnDrag: false,
title: "Drag me to change shape",
icon: new google.maps.MarkerImage("/images/demos/markers/measure-vertex.png", new google.maps.Size(9, 9), new google.maps.Point(0, 0), new google.maps.Point(5, 5))
});
// Add this LatLng to our line and polygon MVCArrays
// Objects added to these MVCArrays automatically update the line and polygon shapes on the map
measure.mvcLine.push(latLng);
measure.mvcPolygon.push(latLng);
// Push this marker to an MVCArray
// This way later we can loop through the array and remove them when measuring is done
measure.mvcMarkers.push(marker);
// Get the index position of the LatLng we just pushed into the MVCArray
// We'll need this later to update the MVCArray if the user moves the measure vertexes
var latLngIndex = measure.mvcLine.getLength() - 1;
// When the user mouses over the measure vertex markers, change shape and color to make it obvious they can be moved
google.maps.event.addListener(marker, "mouseover", function() {
marker.setIcon(new google.maps.MarkerImage("/images/demos/markers/measure-vertex-hover.png", new google.maps.Size(15, 15), new google.maps.Point(0, 0), new google.maps.Point(8, 8)));
});
// Change back to the default marker when the user mouses out
google.maps.event.addListener(marker, "mouseout", function() {
marker.setIcon(new google.maps.MarkerImage("/images/demos/markers/measure-vertex.png", new google.maps.Size(9, 9), new google.maps.Point(0, 0), new google.maps.Point(5, 5)));
});
// When the measure vertex markers are dragged, update the geometry of the line and polygon by resetting the
// LatLng at this position
google.maps.event.addListener(marker, "drag", function(evt) {
measure.mvcLine.setAt(latLngIndex, evt.latLng);
measure.mvcPolygon.setAt(latLngIndex, evt.latLng);
});
// When dragging has ended and there is more than one vertex, measure length, area.
google.maps.event.addListener(marker, "dragend", function() {
if (measure.mvcLine.getLength() > 1) {
measureCalc();
}
});
// If there is more than one vertex on the line
if (measure.mvcLine.getLength() > 1) {
// If the line hasn't been created yet
if (!measure.line) {
// Create the line (google.maps.Polyline)
measure.line = new google.maps.Polyline({
map: map,
clickable: false,
strokeColor: "#FF0000",
strokeOpacity: 1,
strokeWeight: 3,
path:measure. mvcLine
});
}
// If there is more than two vertexes for a polygon
if (measure.mvcPolygon.getLength() > 2) {
// If the polygon hasn't been created yet
if (!measure.polygon) {
// Create the polygon (google.maps.Polygon)
measure.polygon = new google.maps.Polygon({
clickable: false,
map: map,
fillOpacity: 0.25,
strokeOpacity: 0,
paths: measure.mvcPolygon
});
}
}
}
// If there's more than one vertex, measure length, area.
if (measure.mvcLine.getLength() > 1) {
measureCalc();
}
}
function measureCalc() {
// Use the Google Maps geometry library to measure the length of the line
var length = google.maps.geometry.spherical.computeLength(measure.line.getPath());
jQuery("#span-length").text(length.toFixed(1))
// If we have a polygon (>2 vertexes inthe mvcPolygon MVCArray)
if (measure.mvcPolygon.getLength() > 2) {
// Use the Google Maps geometry library tomeasure the area of the polygon
var area = google.maps.geometry.spherical.computeArea(measure.polygon.getPath());
jQuery("#span-area").text(area.toFixed(1));
}
}
function measureReset() {
// If we have a polygon or a line, remove them from the map and set null
if (measure.polygon) {
measure.polygon.setMap(null);
measure.polygon = null;
}
if (measure.line) {
measure.line.setMap(null);
measure.line = null
}
// Empty the mvcLine and mvcPolygon MVCArrays
measure.mvcLine.clear();
measure.mvcPolygon.clear();
// Loop through the markers MVCArray and remove each from the map, then empty it
measure.mvcMarkers.forEach(function(elem, index) {
elem.setMap(null);
});
measure.mvcMarkers.clear();
jQuery("#span-length,#span-area").text(0);
}
I'm trying get the mid point (centroid) and return the Long Lat value. It's kinda like this JSFiddle. The problem is I'm trying to get the mid point (centroid) but alywas getting an error. It's return like this :
I am appreciate if anyone can help :D
Thanks

You can declare LatLngBounds() object first, then extend your bound objects for each marker:
var bounds = new google.maps.LatLngBounds();
var loc = measure.polygon.getPath().b;
for (i = 0; i < loc.length; i++) {
bounds.extend(new google.maps.LatLng(loc[i].lat(), loc[i].lng()));
}
var marker = new google.maps.Marker({
position: bounds.getCenter(),
map: map
});
https://jsfiddle.net/xvbLr993/13/

Related

How to draw a line and a box on gmaps?

I've seen this tool which let you draw a line on gmaps and it generates the js code for you
So the JS is:
var myCoordinates = [
new google.maps.LatLng(48.955410,10.034749),
new google.maps.LatLng(59.648652,29.898030)
];
var polyOptions = {
path: myCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1,
strokeWeight: 3
}
var it = new google.maps.Polyline(polyOptions);
it.setMap(map);
What I would like to do is to start the line from a pin I receive and not a pin I set when I click as per that tool and then I would to draw a infobox at the end of that line (so not where it starts form the pin).
What I am aiming for is to draw a line form a starting point and have an infobox such as per this image below, see the lines on the map
Therefore I can pass the coords here:
new google.maps.LatLng(48.955410,10.034749),
new google.maps.LatLng(59.648652,29.898030)
But how would I target the end of the line and place text there?
With this answer I can define a start and end, but how to draw a box at the end point?
I think you can do it using a marker at the end point of the line, then attaching, for example an infoWindow, at the end and finally hiding the marker.
function initMap() {
var coordinates = {
lat: 40.785845,
lng: -74.020496
};
var coordinates2 = {
lat: 40.805845,
lng: -74.130496
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: coordinates,
scrollwheel: false
});
var marker = new google.maps.Marker({
position: coordinates,
map: map
});
var infoMarker = new google.maps.Marker({
position: coordinates2,
map: map
});
var infowWindow = new google.maps.InfoWindow();
var line = new google.maps.Polyline({
path: [
marker.position,
infoMarker.position
],
strokeColor: "#FF0000",
strokeOpacity: 1,
strokeWeight: 3
});
line.setMap(map);
infowWindow.setContent("<b>Hello world!</b>");
infowWindow.open(map, infoMarker);
infoMarker.setVisible(false);
}
google.maps.event.addDomListener(window, "load", initMap);
Check it working on this jsfiddle

Draggable pin not updating coordinates in Google Maps API

I have this code that allows users to insert pins in Google Maps, by clicking on the map. Now I'm trying to make this pin draggable, so I just added draggable:true, in the initialization of the markers. But this is not updating the field with the coordinates. It only works if the user clicks in another place. What am I missing?
// global "map" variable
var map = null;
var marker = null;
// popup window for pin, if in use
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150,50)
});
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
google.maps.event.trigger(marker, 'click');
return marker;
}
function initialize() {
// the location of the initial pin
var myLatlng = new google.maps.LatLng(-19.919131, -43.938637);
// create the map
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// establish the initial marker/pin
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Property Location",
draggable:true,
icon: {
url: 'https://4.bp.blogspot.com/-nHydF9OdHLw/V8OxZbpJW6I/AAAAAAAAADM/G_QLEm7aScUOc3XwZmc5X8DmMHp7FK3RwCLcB/s1600/BikeSpot-Pin-Logo.png',
// base image is 60x60 px
size: new google.maps.Size(64, 96),
// we want to render # 30x30 logical px (#2x dppx or 'Retina')
scaledSize: new google.maps.Size(32, 48),
// the most top-left point of your marker in the sprite
// (based on scaledSize, not original)
origin: new google.maps.Point(0, 0),
// the "pointer"/anchor coordinates of the marker (again based on scaledSize)
anchor: new google.maps.Point(16, 48)
}
});
// establish the initial div form fields
formlat = myLatlng.lat();
formlng = myLatlng.lng();
document.getElementById("LatLng-Input").value = myLatlng.toUrlValue();
// close popup window
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// removing old markers/pins
google.maps.event.addListener(map, 'click', function(event) {
//call function to create marker
if (marker) {
marker.setMap(null);
marker = null;
}
// Information for popup window if you so chose to have one
/*
marker = createMarker(event.latLng, "name", "<b>Location</b><br>"+event.latLng);
*/
var image = 'https://4.bp.blogspot.com/-nHydF9OdHLw/V8OxZbpJW6I/AAAAAAAAADM/G_QLEm7aScUOc3XwZmc5X8DmMHp7FK3RwCLcB/s1600/BikeSpot-Pin-Logo.png';
var myLatLng = event.latLng ;
/*
var marker = new google.maps.Marker({
by removing the 'var' subsquent pin placement removes the old pin icon
*/
marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title:"Bicicletario",
icon: {
url: 'https://4.bp.blogspot.com/-nHydF9OdHLw/V8OxZbpJW6I/AAAAAAAAADM/G_QLEm7aScUOc3XwZmc5X8DmMHp7FK3RwCLcB/s1600/BikeSpot-Pin-Logo.png',
// base image is 60x60 px
size: new google.maps.Size(64, 96),
// we want to render # 30x30 logical px (#2x dppx or 'Retina')
scaledSize: new google.maps.Size(32, 48),
// the most top-left point of your marker in the sprite
// (based on scaledSize, not original)
origin: new google.maps.Point(0, 0),
// the "pointer"/anchor coordinates of the marker (again based on scaledSize)
anchor: new google.maps.Point(16, 48)
}
});
// populate the form fields with lat & lng
formlat = event.latLng.lat();
formlng = event.latLng.lng();
document.getElementById("LatLng-Input").value = formlat +", "+formlng
});
}
});
}
The HTML with the input I'm receiving the coordinates is:
<div id='map_canvas'/>
<input id='LatLng-Input' size='20' type='text'/>
It's not updating the coordinates because you don't tell it to do so. You have to add a dragend-handler and update your element, where you display the coordinates when the drag of the marker is finished:
marker.addListener('dragend', function(event){
document.getElementById("LatLng-Input").value = event.latLng.lat() + ", " + event.latLng.lng();
});
If you would have an infowindow you would have to update the content of the infowindow:
marker.addListener('dragend', function(event){
infoWindow.setContent(event.latLng.lat() + ", " + event.latLng.lng());
});
If you want to update the coordinates also while dragging, add another handler with 'drag' instead of 'dragend'.

How to get coordinates of outside element dropped on a google map?

I have a google map and a custom element to use as a marker. When I drop the marker from outside the map on the map I need to get the coordinates of that location. How to do this?
".clue_bottom_left img" is the element used as the marker.
Code for drag and drop using jquery-ui:
$(".clue_bottom_left img").draggable({
containment: 'map',
revert: "invalid",
start: function(evt, ui) {
$('.clue_bottom_left img').fadeTo('fast', 0.6, function() {});
},
stop: function(evt, ui) {
$('.clue_bottom_left img').fadeTo('fast', 1.0, function() {});
// INSERT Point
}
});
$('#map').droppable({
drop: function(e, ui) {
$(ui.draggable).draggable();
}
});
Code for creating the map:
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 41.9876644, lng: 22.4192234},
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true, // a way to quickly hide all controls
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
UPDATE:
This is not a duplicate as someone marked it with another post on how to do something when the marker is dropped on the map. I know how to do that. My marker is not actually a marker. Is a image in a div outside the map. And I wondered how to use that image as a marker using drag and drop with jQuery UI.

adding sound to an array of markers - google map javascript

I am new here so I know I don't have any credibility. I am an artist and new to programming so I understand if no one will take this on. I am posting this on the off chance that this is an easy question. -S
This is the code (mostly from the google developer site) to create multiple markers. It works fine and creates a custom icon for each marker.
Each marker should play a different audio file when clicked (right now only the last marker created does). I would also like to change the icon when the audio file is playing. I am using javascript and sound manager 2 to play the audio - but what i am interested in is:
how do i reference each marker in the array so that i can play the specific audio file assigned to that specific marker?
I am hoping i csn do this without XML and a database.
-Sabine
Here is the relevant code:
setMarkers(map, beaches);
}
var beaches = [
['Devotion', 40.710431,-73.948432, 0],
['Tester', 40.711223,-73.958416, 1],
];
function setMarkers(map, locations) {
var image = new google.maps.MarkerImage('biker.png',
// This marker is 20 pixels wide by 32 pixels tall.
new google.maps.Size(32, 32),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at 0,32.
new google.maps.Point(0, 32)
);
var newimage = new google.maps.MarkerImage('biker_click.png',
// This marker is 20 pixels wide by 32 pixels tall.
new google.maps.Size(32, 32),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at 0,32.
new google.maps.Point(0, 32)
);
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape,
title: beach[0],
zIndex: beach[3],
});
}
function markerClick() {
console.log('click');
}
google.maps.event.addListener(marker, 'click', markerClick);
function markerClick() {
var playing = sm2.toggle('http://mm1.ellieirons.com/wp-content/uploads/2012/03/beeps_bubbles.mp3', true);
if (playing) {
this.setIcon(newimage);
} else {
this.setIcon(image);
}
}
Suppose you have an array of URLs:
var sounds = ["http://mm1.ellieirons.com/wp-content/uploads/2012/03/beeps_bubbles.mp3",
"http://mm1.ellieirons.com/wp-content/uploads/2012/03/beeps_bubbles2.mp3"];
Then you could try something like this:
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape,
title: beach[0],
zIndex: beach[3]
});
marker.sound = sounds[i]; //Storing associated sound in marker
google.maps.event.addListener(marker, 'click', markerClick);
}
And modify the handler to this:
function markerClick() {
var playing = sm2.toggle(this.sound, true);
if (playing) {
this.setIcon(newimage);
} else {
this.setIcon(image);
}
}
Something like this..
var beaches = [
['Devotion', 40.710431,-73.948432, 0, 'sound1.mp3'],
['Tester', 40.711223,-73.958416, 1, 'sound2.mp3'],
];
// ...
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape,
title: beach[0],
zIndex: beach[3],
});
google.maps.event.addListener(marker, 'click', function() {
playSound(beach[4]);
});
}
Because you define an anonymous function inside your loop, it has access to the loop's variables (it is a "closure"). You add the name of your sound to the data associated with the beaches, then pass it from the closure to the function (I call it playSound) which actually causes it to play.
Hope this helps, it's not a complete recipe.

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

Categories

Resources