Drawing polyline similar to drawing of polyline in DrawingManager - google-maps-api-3

This is how I draw my polyline where I click the first point and the polyline is drawn after I click the second point on the map canvas:
Sample google.maps.Polyline
This how polyline is drawn with the DrawingManager:
Sample Drawing Manager
I'd like to draw my regular polyline the same way that is drawn by DrawingManager where the line is continued to show where I move my mouse across the map canvas.
Thanks,

This works for me, one important detail was specifying clickable: false when constructing the polyline, otherwise it didn't register the click event on the map.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Complex Polylines</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var poly;
var map;
var existingPolylinePath;
var tempPoly;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {lat: 41.879, lng: -87.624} // Center the map on Chicago, USA.
});
poly = new google.maps.Polyline({
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3,
map: map,
clickable: false
});
tempPoly = new google.maps.Polyline({
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 3,
map: map,
clickable: false
});
// Add a listener for the click event
map.addListener('click', addLatLng);
map.addListener('mousemove', function(event) {
existingPolylinePath = poly.getPath();
if (existingPolylinePath.length > 0) {
tempPoly.setPath([existingPolylinePath.getAt(existingPolylinePath.length - 1), event.latLng]);
}
});
}
// Handles click events on a map, and adds a new point to the Polyline.
function addLatLng(event) {
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear.
path.push(event.latLng);
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
</body>
</html>

You could achieve this my using the map mouseover event. This returns a LatLng, say pointA. If you can write code that will record the previous point that you've drawn, say pointB, then you can render a temporary line from pointA to pointB of a different style in this event.
Let me know if you'd like a code sample.

Related

Googlemaps circle not appearing

I'm having trouble getting a circle to appear on my map, but I'm not getting any errors. Can anyone tell me what I'm doing wrong, please?
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(41.0342375, -77.3066405),
zoom: 8,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.TERRAIN, //style below will be 'shift worker' from snazzy maps
styles: [{"stylers":[{"saturation":-100},{"gamma":1}]},{"elementType":"labels.text.stroke","stylers":[{"visibility":"off"}]},{"featureType":"poi.business","elementType":"labels.text","stylers":[{"visibility":"off"}]},{"featureType":"poi.business","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"poi.place_of_worship","elementType":"labels.text","stylers":[{"visibility":"off"}]},{"featureType":"poi.place_of_worship","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"geometry","stylers":[{"visibility":"simplified"}]},{"featureType":"water","stylers":[{"visibility":"on"},{"saturation":50},{"gamma":0},{"hue":"#50a5d1"}]},{"featureType":"administrative.neighborhood","elementType":"labels.text.fill","stylers":[{"color":"#333333"}]},{"featureType":"road.local","elementType":"labels.text","stylers":[{"weight":0.5},{"color":"#333333"}]},{"featureType":"transit.station","elementType":"labels.icon","stylers":[{"gamma":1},{"saturation":50}]}]
};
var mymap = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
var map = document.getElementById("map-canvas");
$(document).ready(function() {
google.maps.visualRefresh = true;
google.maps.event.addDomListener(window, 'load', initialize);
var populationOptions = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: new google.maps.LatLng(41.0342375, -77.3066405),
radius: 84482
};
// Add the circle for this city to the map.
cityCircle = new google.maps.Circle(populationOptions);
});
Variable scope in Javascript bit you.
The mymap variable is what you need to use for the CircleOptions map property. However it goes out of scope with your initialize function. Your map variable in the anonymous function is just a DIV DOM element, not a google.maps.Map instance.
Simplified working example # http://jsfiddle.net/stevejansen/H5bRg/
There is no reason to combine jQuery's document#ready event handler with google.maps.event.addDomListener(window, 'load', initialize);. They both handle the same DOM event. Just stick with one or the other. It's confusing to use both.

Capture Coordinates in Google Map on User Click

I'm using this code to capture the co-ordinates when user clicks on the map by using below event listener:
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
However this function doesn't get called when user click on already marked location in Map.
Meaning this function is not called for points where mouse pointer changes to hand icon on Google Map.
Need help on capturing these kind of locations.
You should add the click listener on marker will give you the position of marker.
//Add listener
google.maps.event.addListener(marker, "click", function (event) {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
console.log( latitude + ', ' + longitude );
}); //end addListener
Edit:
You need something like this
//Add listener
google.maps.event.addListener(marker, "click", function (event) {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
console.log( latitude + ', ' + longitude );
radius = new google.maps.Circle({map: map,
radius: 100,
center: event.latLng,
fillColor: '#777',
fillOpacity: 0.1,
strokeColor: '#AA0000',
strokeOpacity: 0.8,
strokeWeight: 2,
draggable: true, // Dragable
editable: true // Resizable
});
// Center of map
map.panTo(new google.maps.LatLng(latitude,longitude));
}); //end addListener
Another solution is to place a polygon over the map, same size as the map rectangle, and collect this rectangles clicks.
function initialize() {
var mapDiv = document.getElementById('map-canvas');
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var lat1 = 37.41463623043073;
var lat2 = 37.46915383933881;
var lng1 = -122.1848153442383;
var lng2 = -122.09898465576174;
var rectangle = new google.maps.Polygon({
paths : [
new google.maps.LatLng(lat1, lng1),
new google.maps.LatLng(lat2, lng1),
new google.maps.LatLng(lat2, lng2),
new google.maps.LatLng(lat1, lng2)
],
strokeOpacity: 0,
fillOpacity : 0,
map : map
});
google.maps.event.addListener(rectangle, 'click', function(args) {
console.log('latlng', args.latLng);
});
});
}
Now you get LatLng's for places of interest (and their likes) also.
demo -> http://jsfiddle.net/qmhku4dh/
You're talking about the Point of Interest icons that Google puts on the map.
Would it work for you to remove these icons entirely? You can do that with a Styled Map. To see what this would look like, open the Styled Map Wizard and navigate the map to the area you're interested in.
Click Point of interest under Feature type, and then click Labels under Element type. Finally, click Visibility under Stylers and click the Off radio button under that.
This should remove all of the point of interest icons without affecting the rest of the map styling. With those gone, clicks there will respond to your normal map click event listener.
The Map Style box on the right should show:
Feature type: poi
Element type: labels
Visibility: off
If the result looks like what you want, then click Show JSON at the bottom of the Map Style box. The resulting JSON should like this this:
[
{
"featureType": "poi",
"elementType": "labels",
"stylers": [
{ "visibility": "off" }
]
}
]
You can use that JSON (really a JavaScript object literal) using code similar to the examples in the Styled Maps developer's guide. Also see the MapTypeStyle reference for a complete list of map styles.
This example demonstrates the use of click event listeners on POIs (points of interest). It listens for the click event on a POI icon and then uses the placeId from the event data with a directionsService.route request to calculate and display a route to the clicked place. It also uses the placeId to get more details of the place.
Read the google documentation.
<!DOCTYPE html>
<html>
<head>
<title>POI Click Events</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* 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;
}
.title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
</style>
</head>
<body>
<div id="map"></div>
<div id="infowindow-content">
<img id="place-icon" src="" height="16" width="16">
<span id="place-name" class="title"></span><br>
Place ID <span id="place-id"></span><br>
<span id="place-address"></span>
</div>
<script>
function initMap() {
var origin = {lat: -33.871, lng: 151.197};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 18,
center: origin
});
var clickHandler = new ClickEventHandler(map, origin);
}
/**
* #constructor
*/
var ClickEventHandler = function(map, origin) {
this.origin = origin;
this.map = map;
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
this.placesService = new google.maps.places.PlacesService(map);
this.infowindow = new google.maps.InfoWindow;
this.infowindowContent = document.getElementById('infowindow-content');
this.infowindow.setContent(this.infowindowContent);
// Listen for clicks on the map.
this.map.addListener('click', this.handleClick.bind(this));
};
ClickEventHandler.prototype.handleClick = function(event) {
console.log('You clicked on: ' + event.latLng);
// If the event has a placeId, use it.
if (event.placeId) {
console.log('You clicked on place:' + event.placeId);
// Calling e.stop() on the event prevents the default info window from
// showing.
// If you call stop here when there is no placeId you will prevent some
// other map click event handlers from receiving the event.
event.stop();
this.calculateAndDisplayRoute(event.placeId);
this.getPlaceInformation(event.placeId);
}
};
ClickEventHandler.prototype.calculateAndDisplayRoute = function(placeId) {
var me = this;
this.directionsService.route({
origin: this.origin,
destination: {placeId: placeId},
travelMode: 'WALKING'
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
ClickEventHandler.prototype.getPlaceInformation = function(placeId) {
var me = this;
this.placesService.getDetails({placeId: placeId}, function(place, status) {
if (status === 'OK') {
me.infowindow.close();
me.infowindow.setPosition(place.geometry.location);
me.infowindowContent.children['place-icon'].src = place.icon;
me.infowindowContent.children['place-name'].textContent = place.name;
me.infowindowContent.children['place-id'].textContent = place.place_id;
me.infowindowContent.children['place-address'].textContent =
place.formatted_address;
me.infowindow.open(me.map);
}
});
};
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap"
async defer></script>
</body>
</html>
If you are using npm load-google-maps-api with webpack this worked for me:
const loadGoogleMapApi = require("load-google-maps-api");
loadGoogleMapApi({ key: process.env.GOOGLE_MAP_API_KEY }).then(map => {
let mapCreated = new map.Map(mapElem, {
center: { lat: lat, lng: long },
zoom: 7
});
mapCreated.addListener('click', function(e) {
console.log(e.latLng.lat()); // this gives you access to the latitude value of the click
console.log(e.latLng.lng()); // gives you access to the latitude value of the click
var marker = new map.Marker({
position: e.latLng,
map: mapCreated
});
mapCreated.panTo(e.latLng); // finally this adds red marker to the map on click.
});
});
Next if you are integrating openweatherMap in your app you can use the value of e.latLng.lat() and e.latLng.lng() which I console logged above in your api request. This way:
http://api.openweathermap.org/data/2.5/weather?lat=${e.latLng.lat()}&lon=${e.latLng.lng()}&APPID=${YOUR_API_KEY}
I hope this helps someone as it helped me.
Cheers!

How to save map drawing state (Polygon, Polyline, Markers)

I want to enable drawing on Google Maps like (see this example)
When user finish with drawings he will click on save button to save his drawings in Database or KML file, anything :) .. I do not know how to the save part? Could anyone help me
Here, http://jsfiddle.net/X66L4/1/ try drawing some circles, click on SAVE, then edit the circles by switching to the hand cursor and SAVE again to see the changes.
I show an example to save circles' data, the main idea is to keep a global array for each drawing type (line, polygon, marker, circle), and use a listener on the drawing manager to detect each type being drawn (complete).
var circles = [];
google.maps.event.addDomListener(drawingManager, 'circlecomplete',
function(circle) {
circles.push(circle);
});
The reason to save the entire reference to the drawn object is to continue tracking changes. So you will need an array and listener for each type of drawing.
Then, when you want to save the data (you may wish to do so at every edit), iterate through the arrays and extract the minimum information to rebuild it (center, radius, path, latLng, and so on.)
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html, body, #map_canvas { margin: 0; padding: 0; height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=drawing"></script>
<script type="text/javascript">
var myOptions = {
center: new google.maps.LatLng(-25,177.5),
zoom: 3,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map;
function initialize() {
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.CIRCLE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [google.maps.drawing.OverlayType.CIRCLE]
},
circleOptions: {
editable: true
}
});
drawingManager.setMap(map);
var circles = [];
google.maps.event.addDomListener(drawingManager, 'circlecomplete', function(circle) {
circles.push(circle);
});
google.maps.event.addDomListener(savebutton, 'click', function() {
document.getElementById("savedata").value = "";
for (var i = 0; i < circles.length; i++) {
var circleCenter = circles[i].getCenter();
var circleRadius = circles[i].getRadius();
document.getElementById("savedata").value += "circle((";
document.getElementById("savedata").value +=
circleCenter.lat().toFixed(3) + "," + circleCenter.lng().toFixed(3);
document.getElementById("savedata").value += "), ";
document.getElementById("savedata").value += circleRadius.toFixed(3) + ")\n";
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<button id="savebutton">SAVE</button>
<textarea id="savedata" rows="8" cols="40"></textarea>
<div id="map_canvas"></div>
</body>
</html>
In my experience, it's easier to use map's dataLayer then the drawing manager.
Try out this fiddle.
FiddleLink
Showing the controls:
map.data.setControls(['Polygon']);
map.data.setStyle({
editable: true,
draggable: true
});
in this function you can see the Create, Read (localStorage) and Remove (not in that order):
function loadPolygons(map) {
var data = JSON.parse(localStorage.getItem('geoData'));
map.data.forEach(function (f) {
map.data.remove(f);
});
console.log(data);
map.data.addGeoJson(data)
}

How can I clear a rectangle with Google Maps API V3

I am trying to get the following behaviour. When I click the map I want a rectangle to start appearing. As a move the mouse (not drag) I want the rectangle to adjust itself to fit the first click and the mouse position.
When I click the mouse the second time, I want to capture the corner coordinates (for a spatial search query) and then have the rectangle stop resizing.
On the third mouse click I want the rectangle to disappear.
At the moment the rectangle appears and resizes but it never stops following the mouse.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
div#map { width: 750px; height: 500px; }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"/></script>
<script type="text/javascript">
var start = new google.maps.LatLng();
var clicked=0;
window.onload = function()
{
var settings = {
mapTypeId: google.maps.MapTypeId.TERRAIN, // map type
zoom: 8, // map type
center: new google.maps.LatLng(-33.890542, 151.274856) // coordinates
};
var map = new google.maps.Map(document.getElementById("map"), settings);
rectangle = new google.maps.Rectangle();
google.maps.event.addListener(map, 'click', function(event) {
loc = event.latLng;
if(clicked==0){
$("#start").html(loc.toString());
start=loc;
// start the rectangle
var rectOptions = {
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map
};
rectangle.setOptions(rectOptions);
clicked=1;
}
else if(clicked==1){
$("#end").html(loc.toString());
clicked=2;
alert("clicked "+clicked);
}
else if(clicked==2){
$("#start").html("");
$("#dragged").html("");
$("#end").html("");
clicked=0;
}
});
google.maps.event.addListener(map, 'mousemove', function(event) {
if(clicked==1){
loc = event.latLng;
$("#dragged").html(loc.toString());
$("#dragged").html(loc.toString());
var bounds = new google.maps.LatLngBounds();
bounds.extend(start);
bounds.extend(loc);
rectangle.setBounds(bounds);
}
else if(clicked==2){
alert("mouseover: "+clicked);
rectangle.setMap(null);
}
});
};
</script>
</head>
<body>
<div id="map"></div>
</body>
I've just ran into the same problem and I just noticed how old this post is. Everyone that has this problem, you need to check out https://developers.google.com/maps/documentation/javascript/reference#DrawingManager
use that instead of google.maps.Rectangle(); Check This Out:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=drawing"></script>
<script type="text/javascript">
function initialize() {
// render map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng( 36.175, -115.1363889 ),
mapTypeControl: false,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
// get the DrawingManager - Remember to include &libraries=drawing in the API call
var draw = new google.maps.drawing.DrawingManager({
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT,
drawingModes: [
google.maps.drawing.OverlayType.CIRCLE,
google.maps.drawing.OverlayType.RECTANGLE,
google.maps.drawing.OverlayType.POLYGON
]
},
rectangleOptions: {
fillColor: '#990000',
fillOpacity: .4,
strokeWeight: 3,
strokeColor: '#999',
clickable: true,
editable: true,
zIndex: 1
}
});
// set the cursor to the rectangle
draw.setDrawingMode(google.maps.drawing.OverlayType.RECTANGLE);
// adds a listener for completed overlays, most work done in here
google.maps.event.addListener(draw, 'overlaycomplete', function(event) {
draw.setDrawingMode(null); // put the cursor back to the hand
if (event.type == google.maps.drawing.OverlayType.CIRCLE) {
//do something
}
if (event.type == google.maps.drawing.OverlayType.POLYGON) {
// do something
}
if (event.type == google.maps.drawing.OverlayType.RECTANGLE) {
// on click, unset the overlay, and switch the cursor back to rectangle
google.maps.event.addListener(event.overlay, 'click', function() {
this.setMap(null);
draw.setDrawingMode(google.maps.drawing.OverlayType.RECTANGLE);
});
}
});
// end of initialize
draw.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);

google maps api v3: add point on polyline between two existing points on click polyline event

How can I add point on a polyline between two existing points on a click polyline event?
Thank you!
If you are just talking about a Polyline with only 2 points, you could use the center of a LatLngBounds containing the Polyline. Google maps api v3 doesn't implement the Polyline.getBounds() function, though. So you can extend the Polyline class to include a getBounds function:
google.maps.Polyline.prototype.getBounds = function() {
var bounds = new google.maps.LatLngBounds();
this.getPath().forEach(function(e) {
bounds.extend(e);
});
return bounds;
};
Polyline.getBounds() on a line with only 2 points will contain the area to include this line. The center of this bounds should be the exact center of your line. If the Polyline includes more than 2 points, the center will not fall on the center of the line clicked, but the center of the bounds that includes all points. If you want to use mutli-segment Polylines with this function, it will take more math to calculate which segment was clicked.
Here is a small example using a 2 point Polyline:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Right in Two</title>
<style type="text/css">
#map-canvas {
height: 500px;
}
</style>
<script type="text/javascript"
src="http://www.google.com/jsapi?autoload={'modules':[{name:'maps',version:3,other_params:'sensor=false'}]}"></script>
<script type="text/javascript">
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: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var points = [
new google.maps.LatLng(40.785533,-124.16748),
new google.maps.LatLng(32.700413,-115.469971)
];
var line = new google.maps.Polyline({
map: map,
path: points,
strokeColor: "#FF0000",
strokeWeight: 2,
strokeOpacity: 1.0
});
google.maps.Polyline.prototype.getBounds = function() {
var bounds = new google.maps.LatLngBounds();
this.getPath().forEach(function(e) {
bounds.extend(e);
});
return bounds;
};
google.maps.event.addListener(line, 'click', function(e){
var marker = new google.maps.Marker({
map: map,
position: line.getBounds().getCenter()
});
});
};
google.maps.event.addDomListener(window, 'load', init);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
you just need to calculate the bearing and 50% of the distance - add the verticle there.
above example is the center of the boundary - which is identical.
you may need a temporary boundary object which extends boundaries by the previous and next verticle latlang.

Resources