How can I create a draggable rectangle in map api v3 - javascript

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

Related

Height and width of rectangle api google maps v3

can someone help me? I am trying get width and height of rectangle the google maps api.
I'm doing it this way:
google.maps.event.addListener(drawingManager, 'rectanglecomplete', function (rectangle) {
//height
var height= google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(rectangle.bounds.toJSON().north, rectangle.bounds.toJSON().east),
new google.maps.LatLng(rectangle.bounds.toJSON().south, rectangle.bounds.toJSON().west)
);
//width
var width= google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(rectangle.bounds.toJSON().north, rectangle.bounds.toJSON().east),
new google.maps.LatLng(rectangle.bounds.toJSON().north, rectangle.bounds.toJSON().west)
);
});
You are calculating the wrong distance for the height (NorthEast corner to SouthWest corner). This:
//height
var height= google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(rectangle.bounds.toJSON().north, rectangle.bounds.toJSON().east),
new google.maps.LatLng(rectangle.bounds.toJSON().south, rectangle.bounds.toJSON().west)
);
Should be:
//height
var height= google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(rectangle.bounds.toJSON().north, rectangle.bounds.toJSON().east),
new google.maps.LatLng(rectangle.bounds.toJSON().south, rectangle.bounds.toJSON().east)
);
(or you could make both longitudes .west)
Note that the width will be different at the northern and southern edges if it appears as a rectangle in the map projection.
proof of concept fiddle
code snippet:
// This example requires the Drawing library. Include the libraries=drawing
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=drawing">
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8
});
var rectBounds = new google.maps.LatLngBounds();
var NW = map.getCenter();
var markerNW = new google.maps.Marker({
map: map,
position: NW,
label: "C",
title: NW.toUrlValue(6)
})
rectBounds.extend(map.getCenter());
var NE = google.maps.geometry.spherical.computeOffset(map.getCenter(), 100, 90);
var markerNE = new google.maps.Marker({
map: map,
position: NE,
label: "NE",
title: NE.toUrlValue(6)
});
rectBounds.extend(markerNE.getPosition());
var SW = google.maps.geometry.spherical.computeOffset(map.getCenter(), 100, 180);
var markerSW = new google.maps.Marker({
map: map,
position: SW,
label: "SW",
title: SW.toUrlValue(6)
})
rectBounds.extend(markerSW.getPosition());
var SE = google.maps.geometry.spherical.computeOffset(NE, 100, 180);
var markerSE = new google.maps.Marker({
map: map,
position: SE,
label: "SE",
title: SE.toUrlValue(6)
})
rectBounds.extend(markerSE.getPosition());
var rect = new google.maps.Rectangle({
map: map,
bounds: rectBounds
})
map.fitBounds(rectBounds);
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ['rectangle']
},
markerOptions: {
icon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'
},
circleOptions: {
fillColor: '#ffff00',
fillOpacity: 1,
strokeWeight: 5,
clickable: false,
editable: true,
zIndex: 1
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'rectanglecomplete', function(rectangle) {
//height
var height = google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(rectangle.bounds.toJSON().north, rectangle.bounds.toJSON().east),
new google.maps.LatLng(rectangle.bounds.toJSON().south, rectangle.bounds.toJSON().east)
);
//width
var width = google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(rectangle.bounds.toJSON().north, rectangle.bounds.toJSON().east),
new google.maps.LatLng(rectangle.bounds.toJSON().north, rectangle.bounds.toJSON().west)
);
document.getElementById('dimensions').innerHTML = "height:" + height.toFixed(2) + " m<br>width:" + width.toFixed(2) + " m";
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="dimensions"></div>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=drawing,geometry&callback=initMap" async defer></script>
I managed to solve it like this:
// get the coordinates for the NE and SW corners
            NE = rectangle.bounds.getNorthEast ();
            SW = rectangle.bounds.getSouthWest ();
            // from that, figure out the latitudes and the longitudes
            lat1 = NE.lat ();
            lat2 = SW.lat ();
            lng1 = NE.lng ();
            lng2 = SW.lng ();
            // construct new LatLngs using the coordinates for the horizontal distance between lng1 and lng2
            horizontalLatLng1 = new google.maps.LatLng (lat1, lng1);
            horizontalLatLng2 = new google.maps.LatLng (lat1, lng2);
            // construct new LatLngs using the coordinates for the vertical distance between lat1 and lat2
            verticalLatLng1 = new google.maps.LatLng (lat1, lng1);
            verticalLatLng2 = new google.maps.LatLng (lat2, lng1);
            // work out the distance horizontally
            width = google.maps.geometry.spherical.computeDistanceBetween (horizontalLatLng1, horizontalLatLng2);
            // work out the distance vertically
            height = google.maps.geometry.spherical.computeDistanceBetween (verticalLatLng1, verticalLatLng2);
https://duncan99.wordpress.com/2013/10/19/google-maps-size/

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

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/

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'.

Add multiple event listener on google map API v3 AND MarkerWithLabel

I want to add, for each of my markers, an event on click to center on this one. I use the lib "MarkerWithLabel" and when I click on a marker, the map is zooming on the last marker each time.
Here is my code :
var map = new google.maps.Map(document.getElementById('map-canvas')),
bounds = new google.maps.LatLngBounds(),
marker = [],
grafxUrl = $('#map-canvas').data('grafx'),
image = {
url : grafxUrl + 'universal/icons/pin_locator.png',
size: new google.maps.Size(24, 31),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(12, 31)
};
for (var i = 0; i < response.length; i++) {
marker = new MarkerWithLabel({
position: new google.maps.LatLng(response[i].fLatitude, response[i].fLongitude),
map: map,
icon : image ,
title : (i+1)+' '+response[i].sName,
labelContent: (i+1),
labelAnchor: new google.maps.Point(3, 25),
labelClass: "markerNum", // the CSS class for the label
});
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(15);
map.setCenter(marker.position);
});
bounds.extend(marker.position);
//now fit the map to the newly inclusive bounds
map.fitBounds(bounds);
}
What is wrong with my script ?
Thanks a lot.
Here is a complete example on how to extend a bounds object to display all markers on the map.
function initialize() {
var southWest = new google.maps.LatLng(40.744656, -74.005966);
var northEast = new google.maps.LatLng(34.052234, -118.243685);
var lngSpan = northEast.lng() - southWest.lng();
var latSpan = northEast.lat() - southWest.lat();
var map = new google.maps.Map(document.getElementById("map-canvas"), {
zoom: 12,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Create the bounds object
var bounds = new google.maps.LatLngBounds();
// Create random markers
for (var i = 0; i < 100; i++) {
// Calculate a random position
var position = new google.maps.LatLng(southWest.lat() + latSpan * Math.random(), southWest.lng() + lngSpan * Math.random());
var marker = new google.maps.Marker({
position: position,
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
map.setZoom(5);
map.setCenter(marker.position);
}
})(marker, i));
// Extend the bounds with the last marker position
bounds.extend(position);
}
// Fit map to the extended bounds
map.fitBounds(bounds);
}
initialize();
This creates 100 random markers within the defined bounds (southWest / northEast coords) then extends a bounds object and finally fit the map to this bounds object. See how the marker variable is defined (within the for loop) and how the fitBounds() is called (outside the for loop). The same should apply to your code.
Below is a working demo. Hope this helps!
JSFiddle 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