Related
I am new to Google Maps and I need to receive an alert when the marker moves outside the circles, I have already created the map and added some circles to represent the areas in which the marker can stay, outside of them I need to show a alert announcing that this is not a coverage area.
My code is the following:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento sin título</title>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=places&v=weekly" defer></script>
<script type="text/javascript">
const citymap = {
escalon: {
center: { lat: 13.701984532461921, lng: -89.23395010808454 },
},
};
const citymap1 = {
matriz: {
center: { lat: 13.699526, lng: -89.196691 },
},
};
const citymap2 = {
plaza: {
center: { lat: 13.699581, lng: -89.189770 },
},
};
const citymap3 = {
ahuachapan: {
center: { lat: 13.920266, lng: -89.847658 },
},
};
const citymap4 = {
sanMiguel: {
center: { lat: 13.484937, lng: -88.177339 },
},
};
const citymap5 = {
santaAna: {
center: { lat: 13.993704, lng: -89.556913 },
},
};
const citymap6 = {
sonsonate: {
center: { lat: 13.720177, lng: -89.727801 },
},
};
function initialize() {
// Creating map object
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 12,
center: new google.maps.LatLng(13.701277, -89.224468),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var vMarker = new google.maps.Marker({
position: new google.maps.LatLng(13.701277, -89.224468),
draggable: true
});
google.maps.event.addListener(vMarker, 'dragend', function (evt) {
$("#txtLat").val("https://www.google.es/maps/dir/" + evt.latLng.lat().toFixed(6) + ", " + evt.latLng.lng().toFixed(6));
map.panTo(evt.latLng);
});
for (const city in citymap) {
// Add the circle for this city to the map.
const vMarker = new google.maps.Marker({
position: new google.maps.LatLng(13.701277, -89.224468),
draggable: true
});
}
for (const city in citymap) {
// Add the circle for this city to the map.
const cityCircle = new google.maps.Circle({
strokeColor: "#0066cc",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0066cc",
fillOpacity: 0.35,
map,
center: citymap[city].center,
radius: 8000,
});
}
for (const city in citymap1) {
// Add the circle for this city to the map.
const cityCircle = new google.maps.Circle({
strokeColor: "#0066cc",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0066cc",
fillOpacity: 0.35,
map,
center: citymap1[city].center,
radius: 5000,
});
}
for (const city in citymap2) {
// Add the circle for this city to the map.
const cityCircle = new google.maps.Circle({
strokeColor: "#0066cc",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0066cc",
fillOpacity: 0.35,
map,
center: citymap2[city].center,
radius: 5000,
});
}
for (const city in citymap3) {
// Add the circle for this city to the map.
const cityCircle = new google.maps.Circle({
strokeColor: "#0066cc",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0066cc",
fillOpacity: 0.35,
map,
center: citymap3[city].center,
radius: 7000,
});
}
for (const city in citymap4) {
// Add the circle for this city to the map.
const cityCircle = new google.maps.Circle({
strokeColor: "#0066cc",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0066cc",
fillOpacity: 0.35,
map,
center: citymap4[city].center,
radius: 7000,
});
}
for (const city in citymap5) {
// Add the circle for this city to the map.
const cityCircle = new google.maps.Circle({
strokeColor: "#0066cc",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0066cc",
fillOpacity: 0.35,
map,
center: citymap5[city].center,
radius: 7000,
});
}
for (const city in citymap6) {
// Add the circle for this city to the map.
const cityCircle = new google.maps.Circle({
strokeColor: "#0066cc",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0066cc",
fillOpacity: 0.35,
map,
center: citymap6[city].center,
radius: 7000,
});
}
// centers the map on markers coords
map.setCenter(vMarker.position);
// adds the marker on the map
vMarker.setMap(map);
}
</script>
</head>
<body onload="initialize();">
<div id='map_canvas' style='width: auto; height: 500px;'></div>
</body>
</html>
I have left you this example code in order to have a broader panorama of my problem, because precisely what I am trying to do is a type of home delivery and the areas in blue marked on the map are the areas in which If there is coverage of my home delivery, but if the marker is located outside of them, or if the client moves them outside of them, I need the alert to be displayed to warn that it cannot be, I appreciate all the support, greetings.
You can do this by getting the bounds getBounds() of the circle and check if the location of the marker is within those bounds like so:
function init() {
var
contentCenter = '<span class="infowin">Center Marker (draggable)</span>',
contentA = '<span class="infowin">Marker A (draggable)</span>',
contentB = '<span class="infowin">Marker B (draggable)</span>';
var
latLngCenter = new google.maps.LatLng(37.081476, -94.510574),
latLngCMarker = new google.maps.LatLng(37.0814, -94.5105),
latLngA = new google.maps.LatLng(37.2, -94.1),
latLngB = new google.maps.LatLng(38, -93),
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: latLngCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
}),
markerCenter = new google.maps.Marker({
position: latLngCMarker,
title: 'Location',
map: map,
draggable: true
}),
infoCenter = new google.maps.InfoWindow({
content: contentCenter
}),
markerA = new google.maps.Marker({
position: latLngA,
title: 'Location',
map: map,
draggable: true
}),
infoA = new google.maps.InfoWindow({
content: contentA
}),
markerB = new google.maps.Marker({
position: latLngB,
title: 'Location',
map: map,
draggable: true
}),
infoB = new google.maps.InfoWindow({
content: contentB
})
// exemplary setup:
// Assumes that your map is signed to the var "map"
// Also assumes that your marker is named "marker"
,
circle = new google.maps.Circle({
map: map,
clickable: false,
// metres
radius: 100000,
fillColor: '#fff',
fillOpacity: .6,
strokeColor: '#313131',
strokeOpacity: .4,
strokeWeight: .8
});
// attach circle to marker
circle.bindTo('center', markerCenter, 'position');
var
// get the Bounds of the circle
bounds = circle.getBounds()
// Note spans
,
noteA = jQuery('.bool#a'),
noteB = jQuery('.bool#b');
noteA.text(bounds.contains(latLngA));
noteB.text(bounds.contains(latLngB));
// get some latLng object and Question if it's contained in the circle:
google.maps.event.addListener(markerCenter, 'dragend', function() {
latLngCenter = new google.maps.LatLng(markerCenter.position.lat(), markerCenter.position.lng());
bounds = circle.getBounds();
noteA.text(bounds.contains(latLngA));
noteB.text(bounds.contains(latLngB));
});
google.maps.event.addListener(markerA, 'dragend', function() {
latLngA = new google.maps.LatLng(markerA.position.lat(), markerA.position.lng());
noteA.text(bounds.contains(latLngA));
});
google.maps.event.addListener(markerB, 'dragend', function() {
latLngB = new google.maps.LatLng(markerB.position.lat(), markerB.position.lng());
noteB.text(bounds.contains(latLngB));
});
google.maps.event.addListener(markerCenter, 'click', function() {
infoCenter.open(map, markerCenter);
});
google.maps.event.addListener(markerA, 'click', function() {
infoA.open(map, markerA);
});
google.maps.event.addListener(markerB, 'click', function() {
infoB.open(map, markerB);
});
google.maps.event.addListener(markerCenter, 'drag', function() {
infoCenter.close();
noteA.html("draggin…");
noteB.html("draggin…");
});
google.maps.event.addListener(markerA, 'drag', function() {
infoA.close();
noteA.html("draggin…");
});
google.maps.event.addListener(markerB, 'drag', function() {
infoB.close();
noteB.html("draggin…");
});
};
body {
margin: 0;
padding: 0
}
html,
body,
#map {
height: 100%;
font-family: Arial, sans-serif;
font-size: .9em;
color: #fff;
}
#note {
text-align: center;
padding: .3em; 10px;
background: #009ee0;
}
.bool {
font-style: italic;
color: #313131;
}
.info {
display: inline-block;
width: 40%;
text-align: center;
}
.infowin {
color: #313131;
}
#title,
.bool{
font-weight: bold;
}
<div id="note">
<span id="title">»Inside the circle?«</span>
<hr />
<span class="info">Marker <strong>A</strong>:
<span id="a" class="bool"></span>
</span> ←♦→
<span class="info">Marker <strong>B</strong>:
<span id="b" class="bool"></span>
</span>
</div>
<div id="map">test</div>
<script src="https://maps.googleapis.com/maps/api/js?callback=init&libraries=&v=weekly&key=YOUR_API_KEY" async></script>
I´m creating a map out of polygons to show the different districts of a city. Each polygon (district) should be clickable to another website (a sub-page with information about this area). I already added an add.listener and I can see that there is a link behind a polygon when I hover over the polygon but it is not clickable.
This is what I have so far for one polygon:
<body>
<h1>Headline</h1>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center:{lat:52.516754,lng:13.415202},
mapTypeId: 'terrain'
});
//Define the LatLng coordinates for the polygon's path DistrictOne
var DistrictOneCoords = [
{lat:52.528198300, lng:13.424935300},
{lat:52.527989500, lng:13.423905300},
{lat:52.525065200, lng:13.420386300},
{lat:52.522819700, lng:13.426480300},
{lat:52.521148500, lng:13.429141000},
{lat:52.519111700, lng:13.427596100},
{lat:52.528198300, lng:13.424935300}
];
// Construct the polygon.
var DistrictOne = new google.maps.Polygon({
paths: DistrictOneCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
DistrictOne.setMap(map);
}
// link
google.maps.event.addListener(DistrictOne, "click", function(event) { window.location.href = "https://www.berlin.de" });
</script>
As I already mentioned I'm not able to click the link.
With the posted code, I get a javascript error:
Uncaught ReferenceError: google is not defined
Your "click" listener is outside of the initMap function, so it is executing before the Google Maps Javascript API v3 has loaded.
Move if inside the initMap function:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center:{lat:52.516754,lng:13.415202},
mapTypeId: 'terrain'
});
//Define the LatLng coordinates for the polygon's path DistrictOne
var DistrictOneCoords = [
{lat:52.528198300, lng:13.424935300},
{lat:52.527989500, lng:13.423905300},
{lat:52.525065200, lng:13.420386300},
{lat:52.522819700, lng:13.426480300},
{lat:52.521148500, lng:13.429141000},
{lat:52.519111700, lng:13.427596100},
{lat:52.528198300, lng:13.424935300}
];
// Construct the polygon.
var DistrictOne = new google.maps.Polygon({
paths: DistrictOneCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
DistrictOne.setMap(map);
// link
google.maps.event.addListener(DistrictOne, "click", function(event) {
window.location.href = "https://www.berlin.de"
});
}
proof of concept fiddle
code snippet:
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {
lat: 52.516754,
lng: 13.415202
},
mapTypeId: 'terrain'
});
//Define the LatLng coordinates for the polygon's path DistrictOne
var DistrictOneCoords = [{
lat: 52.528198300,
lng: 13.424935300
},
{
lat: 52.527989500,
lng: 13.423905300
},
{
lat: 52.525065200,
lng: 13.420386300
},
{
lat: 52.522819700,
lng: 13.426480300
},
{
lat: 52.519111700,
lng: 13.427596100
},
{
lat: 52.521148500,
lng: 13.429141000
},
{
lat: 52.528198300,
lng: 13.424935300
}
];
// Construct the polygon.
var DistrictOne = new google.maps.Polygon({
paths: DistrictOneCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
DistrictOne.setMap(map);
// link
google.maps.event.addListener(DistrictOne, "click", function(event) {
console.log('click, set window.location.href = "https://www.berlin.de"');
// uncomment the line below to make it redirect
// window.location.href = "https://www.berlin.de"
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
As per your given code. I am implemented polygon in my local.
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center:{lat:52.516754,lng:13.415202},
mapTypeId: 'terrain'
});
//Define the LatLng coordinates for the polygon's path DistrictOne
var DistrictOneCoords = [
{lat:52.528198300, lng:13.424935300},
{lat:52.527989500, lng:13.423905300},
{lat:52.525065200, lng:13.420386300},
{lat:52.522819700, lng:13.426480300},
{lat:52.521148500, lng:13.429141000},
{lat:52.519111700, lng:13.427596100},
{lat:52.528198300, lng:13.424935300}
];
// Construct the polygon.
var DistrictOne = new google.maps.Polygon({
paths: DistrictOneCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
DistrictOne.setMap(map);
addEventFunction(DistrictOne);
}
// link
function addEventFunction(DistrictOne) {
google.maps.event.addListener(DistrictOne, "click", function(event) { window.location.href = "https://www.berlin.de" });
}
initMap();
My code is:
// Create an object containing LatLng, population.
var cityPoints = {};
cityPoints[0] = {
center: new google.maps.LatLng(41.878113, -87.629798),
id: 0,
addr: 'avenue0',
magnitude: 100000
};
cityPoints[1] = {
center: new google.maps.LatLng(40.714352, -74.005973),
id: 'siv1',
addr: 'avenue1',
magnitude: 100000
};
cityPoints[2] = {
center: new google.maps.LatLng(34.052234, -118.243684),
id: 'siv2',
addr: 'avenue2',
magnitude: 100000
}
var cityCircle;
var infoWindow = new google.maps.InfoWindow({size: new google.maps.Size(150,150)});
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(37.09024, -95.712891),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
for (i in cityPoints) {
var magnitudeOptions = {
map: map,
center: cityPoints[i].center,
radius: cityPoints[i].magnitude,
id:cityPoints[i].id,
addr:cityPoints[i].addr,
infoWindowIndex: i,
strokeColor: '#2d7142',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#7faf8e',
fillOpacity: 0.2
};
cityCircle = new google.maps.Circle(magnitudeOptions);
google.maps.event.addListener(cityCircle, 'click', (function(cityCircle, i) {
return function() {
infoWindow.setContent(cityPoints[i].id + " " + cityPoints[i].addr);
infoWindow.setPosition(cityCircle.getCenter());
infoWindow.open(map);
}
})(cityCircle, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize);
function add()
{
alert(cityCircle.get('id'));
alert(cityCircle.get('addr'));
/* $('#siv2').css('color','red'); */
alert($('#siva2').length);
}
I want to google circle act as markers. I just completed that task now additionally i need to change color of circle.
I want to change color of already drawn google map circles with help of already generated google circle Id
Is this Possible???
One option would be to push the circles as you create them into an array, so you can access them later (say circles =[];).
Iterate through the array setting the 'fillColor' property of each circle (and whatever else you want to change).
for (var i = 0; i < circles.length; i++) {
if (circles[i].get('fillColor') == "#FF0000") {
circles[i].setOptions({fillColor:'#7faf8e'});
} else {
circles[i].setOptions({fillColor: "#FF0000"});
}
}
proof of concept fiddle
code snippet:
var circles = [];
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(37.09024, -95.712891),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
for (i in cityPoints) {
var magnitudeOptions = {
map: map,
center: cityPoints[i].center,
radius: cityPoints[i].magnitude,
id: cityPoints[i].id,
addr: cityPoints[i].addr,
infoWindowIndex: i,
strokeColor: '#2d7142',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#7faf8e',
fillOpacity: 0.2
};
cityCircle = new google.maps.Circle(magnitudeOptions);
circles.push(cityCircle);
google.maps.event.addListener(cityCircle, 'click', (function(cityCircle, i) {
return function() {
infoWindow.setContent(cityPoints[i].id + " " + cityPoints[i].addr);
infoWindow.setPosition(cityCircle.getCenter());
infoWindow.open(map);
}
})(cityCircle, i));
}
google.maps.event.addDomListener(document.getElementById('toggleCircles'), 'click', function() {
for (var i = 0; i < circles.length; i++) {
if (circles[i].get('fillColor') == "#FF0000") {
circles[i].setOptions({
fillColor: '#7faf8e'
});
} else {
circles[i].setOptions({
fillColor: "#FF0000"
});
}
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
// Create an object containing LatLng, population.
var cityPoints = {};
cityPoints[0] = {
center: new google.maps.LatLng(41.878113, -87.629798),
id: 0,
addr: 'avenue0',
magnitude: 100000
};
cityPoints[1] = {
center: new google.maps.LatLng(40.714352, -74.005973),
id: 'siv1',
addr: 'avenue1',
magnitude: 100000
};
cityPoints[2] = {
center: new google.maps.LatLng(34.052234, -118.243684),
id: 'siv2',
addr: 'avenue2',
magnitude: 100000
}
var cityCircle;
var infoWindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 150)
});
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input type="button" value="toggle" id="toggleCircles" />
<div id="map-canvas"></div>
If you want to set the color of the circle by its Id, then use an associative array indexed by the id:
circles[cityCircle.id] = cityCircle;
Then change the color like this:
var circleId = document.getElementById('circleId').value;
var circle = circles[circleId];
if (circle.get('fillColor') == "#FF0000") {
circle.setOptions({fillColor: '#7faf8e'});
} else {
circle.setOptions({fillColor: "#FF0000"});
}
proof of concept fiddle
code snippet:
var circles = [];
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(37.09024, -95.712891),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
for (i in cityPoints) {
var magnitudeOptions = {
map: map,
center: cityPoints[i].center,
radius: cityPoints[i].magnitude,
id: cityPoints[i].id,
addr: cityPoints[i].addr,
infoWindowIndex: i,
strokeColor: '#2d7142',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#7faf8e',
fillOpacity: 0.2
};
cityCircle = new google.maps.Circle(magnitudeOptions);
circles[cityCircle.id] = cityCircle;
document.getElementById('circleIds').innerHTML += cityCircle.id + "<br>";
google.maps.event.addListener(cityCircle, 'click', (function(cityCircle, i) {
return function() {
infoWindow.setContent(cityPoints[i].id + " " + cityPoints[i].addr);
infoWindow.setPosition(cityCircle.getCenter());
infoWindow.open(map);
}
})(cityCircle, i));
}
google.maps.event.addDomListener(document.getElementById('toggleCircles'), 'click', function() {
var circleId = document.getElementById('circleId').value;
var circle = circles[circleId];
if (circle.get('fillColor') == "#FF0000") {
circle.setOptions({
fillColor: '#7faf8e'
});
} else {
circle.setOptions({
fillColor: "#FF0000"
});
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
// Create an object containing LatLng, population.
var cityPoints = {};
cityPoints[0] = {
center: new google.maps.LatLng(41.878113, -87.629798),
id: 0,
addr: 'avenue0',
magnitude: 100000
};
cityPoints[1] = {
center: new google.maps.LatLng(40.714352, -74.005973),
id: 'siv1',
addr: 'avenue1',
magnitude: 100000
};
cityPoints[2] = {
center: new google.maps.LatLng(34.052234, -118.243684),
id: 'siv2',
addr: 'avenue2',
magnitude: 100000
}
var cityCircle;
var infoWindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 150)
});
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input type="button" value="toggle" id="toggleCircles" />
<input value="siv2" id="circleId" />
<div id="circleIds"></div>
<div id="map-canvas"></div>
I am trying to fill an area that is bordered by polylines that are snapped to roads. Here is my code:
var pos = new google.maps.LatLng(29.744860,-95.361302);
var myOptions = {
zoom: 12,
center: pos,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), myOptions);
map.setCenter(pos);
roadTrip1 = [
new google.maps.LatLng(29.692093, -95.377307),
new google.maps.LatLng(29.813047,-95.399361),
new google.maps.LatLng(29.692093, -95.377307)
];
var traceroadTrip1 = new google.maps.Polyline({
path: roadTrip1,
strokeColor: "red",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
});
var service1 = new google.maps.DirectionsService(),traceroadTrip1,snap_path=[];
traceroadTrip1.setMap(map);
for(j=0;j<roadTrip1.length-1;j++){
service1.route({origin: roadTrip1[j],destination: roadTrip1[j+1],travelMode: google.maps.DirectionsTravelMode.DRIVING},function(result, status) {
if(status == google.maps.DirectionsStatus.OK) {
snap_path = snap_path.concat(result.routes[0].overview_path);
traceroadTrip1.setPath(snap_path);
}
});
}
I'm not too familiar with javascript and I'm hoping it's easy to create a polygon from polylines that are snapped to roads. Once I have a polygon I'd like to color the area.
Thanks for any and all help.
Change the google.maps.Polyline to a google.maps.Polygon.
var traceroadTrip1 = new google.maps.Polygon({
path: roadTrip1,
strokeColor: "red",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
proof of concept fiddle
code snippet:
function initialize() {
var pos = new google.maps.LatLng(29.813047, -95.399361);
var myOptions = {
zoom: 11,
center: pos,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), myOptions);
map.setCenter(pos);
roadTrip1 = [
new google.maps.LatLng(29.692093, -95.377307),
new google.maps.LatLng(29.813047, -95.399361),
new google.maps.LatLng(29.692093, -95.377307)
];
var traceroadTrip1 = new google.maps.Polygon({
path: roadTrip1,
strokeColor: "red",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
var service1 = new google.maps.DirectionsService(),
traceroadTrip1, snap_path = [];
var bounds = new google.maps.LatLngBounds();
traceroadTrip1.setMap(map);
for (j = 0; j < roadTrip1.length - 1; j++) {
service1.route({
origin: roadTrip1[j],
destination: roadTrip1[j + 1],
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
snap_path = snap_path.concat(result.routes[0].overview_path);
traceroadTrip1.setPath(snap_path);
for (var i = 0; i < traceroadTrip1.getPath().getLength(); i++) {
bounds.extend(traceroadTrip1.getPath().getAt(i));
}
map.fitBounds(bounds);
}
});
}
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
I have a Google Map. When a user clicks, it places a "start" marker. The second click yields a polyline between the first click and the second click, and adds an "end" marker. The third click adds another data point to the polyline, and moves the "end" marker to the most recent click. Nothing special:
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 13
});
map.addListener('click', insertDataPoint);
polyline = new google.maps.Polyline({
strokeColor: '#000000',
strokeOpacity: 0.7,
strokeWeight: 3
});
polyline.setMap(map);
plots = [];
... // Bunch of other code that isn't important
function insertDataPoint(e) {
var path = polyline.getPath();
path.push(e.latLng);
// Logic to set up marker or circle
if (plots.length == 0) {
// Case: first click
startMarker.setPosition(e.latLng);
startMarker.setMap(map);
plots.push(startMarker);
} else {
if (plots.length != 1) {
// Case: we have intermediate points between start and end
var plot = plots.pop();
var marker = new google.maps.Marker({
position: plot.getPosition(),
icon: {
path: google.maps.SymbolPath.CIRCLE,
fillColor: '#ffffff',
fillOpacity: 0.6,
strokeColor: '#ffffff',
strokeOpacity: 0.8,
strokeWeight: 2,
scale: 3
}
});
marker.setMap(map);
plots.push(marker);
}
// Case: add an end marker
endMarker.setPosition(e.latLng);
if (plots.length == 1) {
endMarker.setMap(map);
}
plots.push(endMarker);
}
}
I'd like to get the plotted points in GeoJSON format. I know Google recently released the Data layer API with the .toGeoJson() call, but, naturally, the data is empty because it was not added to the Data layer:
map.data.toGeoJson( function(data) {
alert(JSON.stringify(data)); // {"type":"FeatureCollections", "features":[]}
So the question is how do I add my data -- the markers and polyline -- to the Data layer so I can get that sweet GeoJSON?
Note -- I understand that the Data layer has functionality that allows users to draw on the map, but I need to do it my way.
This will create geoJSON representing the polyline and add it to the data layer:
function exportGeoJson() {
var geoJson = {
"type": "FeatureCollection",
"features": []
};
var polylineFeature = {
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": []
},
"properties": {}
};
for (var i = 0; i < polyline.getPath().getLength(); i++) {
var pt = polyline.getPath().getAt(i);
polylineFeature.geometry.coordinates.push([
pt.lng(), pt.lat()]);
}
geoJson.features.push(polylineFeature);
document.getElementById('geojson').value = JSON.stringify(geoJson);
polyline.setPath([]);
map.data.addGeoJson(geoJson);
// Set the stroke width, and fill color for each polygon
map.data.setStyle({
strokeColor: 'green',
strokeWeight: 2
});
map.data.toGeoJson( function(data) {
document.getElementById('exported').value=JSON.stringify(data)
});
}
proof of concept fiddle
code snippet:
var polyline, map;
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 13
});
map.addListener('click', insertDataPoint);
polyline = new google.maps.Polyline({
strokeColor: '#000000',
strokeOpacity: 0.7,
strokeWeight: 3
});
polyline.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
plots = [];
// Bunch of other code that isn't important
function insertDataPoint(e) {
var path = polyline.getPath();
path.push(e.latLng);
// Logic to set up marker or circle
if (plots.length == 0) {
// Case: first click
startMarker.setPosition(e.latLng);
startMarker.setMap(map);
plots.push(startMarker);
} else {
if (plots.length != 1) {
// Case: we have intermediate points between start and end
var plot = plots.pop();
var marker = new google.maps.Marker({
position: plot.getPosition(),
icon: {
path: google.maps.SymbolPath.CIRCLE,
fillColor: '#ffffff',
fillOpacity: 0.6,
strokeColor: '#ffffff',
strokeOpacity: 0.8,
strokeWeight: 2,
scale: 3
}
});
marker.setMap(map);
plots.push(marker);
}
// Case: add an end marker
endMarker.setPosition(e.latLng);
if (plots.length == 1) {
endMarker.setMap(map);
}
plots.push(endMarker);
}
}
function exportGeoJson() {
var geoJson = {
"type": "FeatureCollection",
"features": []
};
var polylineFeature = {
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": []
},
"properties": {}
};
for (var i = 0; i < polyline.getPath().getLength(); i++) {
var pt = polyline.getPath().getAt(i);
polylineFeature.geometry.coordinates.push([
pt.lng(), pt.lat()
]);
}
geoJson.features.push(polylineFeature);
document.getElementById('geojson').value = JSON.stringify(geoJson);
polyline.setPath([]);
map.data.addGeoJson(geoJson);
// Set the stroke width, and fill color for each polygon
map.data.setStyle({
strokeColor: 'green',
strokeWeight: 2
});
map.data.toGeoJson(function(data) {
document.getElementById('exported').value = JSON.stringify(data)
});
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?"></script>
<input type="button" onclick="exportGeoJson()" value="export GeoJson" />
<div id="map" style="border: 2px solid #3872ac;"></div>
<textarea id="geojson" rows="10" cols="70"></textarea>
<br><b>Exported</b>
<br>
<textarea id="exported" rows="10" cols="70"></textarea>