Extract polyline from Google map to GeoJSON - javascript

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>

Related

convert decoded path to coordinates in javascript?

I have this Encoded path encodedPath which equally oyky#e}|kGpv#kzE, then i tried to decode it using decodePath like this:
decodeString = google.maps.geometry.encoding.decodePath(encodeString);
here is when i console log it `console.log(decodeString);
but when I alert it, this is the exact data:
(9.5684, 44.062430000000006),(9.559510000000001, 44.097530000000006)
So, my question is, Is this data convertable to path again and draw polyline with it ?
because when I tried to draw a polyline like this:
var path = [
(9.5684, 44.062430000000006),
(9.559510000000001, 44.097530000000006)
]
var polyline = new google.maps.Polyline({
path: d,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 5
});
polyline.setMap(map);
It is showing this:
InvalidValueError: at index 0: not a LatLng or LatLngLiteral with finite coordinates: not an Object
google.maps.geometry.encoding.decodePath returns an array of google.maps.LatLng objects, you can pass the value returned directly into the path property of the polyline:
var poly = new google.maps.Polyline({
strokeColor: '#000000',
strokeOpacity: 1,
strokeWeight: 3,
map: map,
path: google.maps.geometry.encoding.decodePath("oyky#e}|kGpv#kzE")
});
(your path array is not a valid JavaScript array)
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: {
lat: 34.366,
lng: -89.519
}
});
var poly = new google.maps.Polyline({
strokeColor: '#000000',
strokeOpacity: 1,
strokeWeight: 3,
map: map,
path: google.maps.geometry.encoding.decodePath("oyky#e}|kGpv#kzE")
});
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < poly.getPath().getLength(); i++) {
bounds.extend(poly.getPath().getAt(i));
console.log(poly.getPath().getAt(i).toUrlValue(6));
}
map.fitBounds(bounds);
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
<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=geometry&callback=initMap" async defer></script>

How to link a Google Maps Polygon to another website?

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();

Google maps JavaScript data_layer multiple styles

I have 3 Polygons in google maps javascript initialized like this:
map.data.add({geometry: new google.maps.Data.Polygon([google.maps.geometry.encoding.decodePath(path), google.maps.geometry.encoding.decodePath(path2), ])})
map.data.add({geometry: new google.maps.Data.Polygon([google.maps.geometry.encoding.decodePath(path2), google.maps.geometry.encoding.decodePath(path3), ])})
map.data.add({geometry: new google.maps.Data.Polygon([google.maps.geometry.encoding.decodePath(path3) ])})
I set the style with this code:
map.data.setStyle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
This sets the style of all 3 Polygon´s. But how can I set a different style for each polygon?
One option for styling the polygons differently is to give them unique properties that determine the style. For example:
map.data.add({
geometry: new google.maps.Data.Polygon([google.maps.geometry.encoding.decodePath(path)]),
properties: {
color: 'blue'
}
})
map.data.add({
geometry: new google.maps.Data.Polygon([google.maps.geometry.encoding.decodePath(path2)]),
properties: {
color: 'green'
}
})
map.data.add({
geometry: new google.maps.Data.Polygon([google.maps.geometry.encoding.decodePath(path3)]),
properties: {
color: 'orange'
}
});
Then create a styling function that uses that property to set the style (modified from the Google example: https://developers.google.com/maps/documentation/javascript/examples/layer-data-dynamic):
map.data.setStyle(function(feature) {
var color = feature.getProperty('color');
return /** #type {!google.maps.Data.StyleOptions} */ ({
fillColor: color,
strokeColor: color,
strokeWeight: 2
});
});
proof of concept fiddle
proof of concept with nested polygons
code snippet:
var geocoder;
var map;
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListener(map, 'click', function(e) {
console.log(e.latLng.toUrlValue(6));
})
var pathCoords = [{lat: 37.4687,lng: -122.151627},
{lat: 37.453575,lng: -122.165704},
{lat: 37.453575,lng: -122.141156}
];
var pathCoords2 = [{lat: 37.437902,lng: -122.174802},
{lat: 37.425089,lng: -122.182355},
{lat: 37.425225,lng: -122.163987}
];
var pathCoords3 = [{lat: 37.431087,lng: -122.103562},
{lat: 37.415409,lng: -122.114549},
{lat: 37.415954,lng: -122.096009}
];
function convert2LatLng(input) {
var pathLatLng = [];
for (var i = 0; i < input.length; i++) {
var pt = new google.maps.LatLng(input[i].lat, input[i].lng);
pathLatLng.push(pt);
}
return pathLatLng;
}
var path = google.maps.geometry.encoding.encodePath(convert2LatLng(pathCoords));
var path2 = google.maps.geometry.encoding.encodePath(convert2LatLng(pathCoords2));
var path3 = google.maps.geometry.encoding.encodePath(convert2LatLng(pathCoords3));
map.data.add({
geometry: new google.maps.Data.Polygon([google.maps.geometry.encoding.decodePath(path)]),
properties: {
color: 'blue'
}
})
map.data.add({
geometry: new google.maps.Data.Polygon([google.maps.geometry.encoding.decodePath(path2)]),
properties: {
color: 'green'
}
})
map.data.add({
geometry: new google.maps.Data.Polygon([google.maps.geometry.encoding.decodePath(path3)]),
properties: {
color: 'orange'
}
});
// Color each letter gray. Change the color when the isColorful property
// is set to true.
map.data.setStyle(function(feature) {
var color = feature.getProperty('color');
return /** #type {!google.maps.Data.StyleOptions} */ ({
fillColor: color,
strokeColor: color,
strokeWeight: 2
});
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>

How to make a circle around a particular city on a map?

I am working on a project in which I want to make a circle around the location of an item on a google map. In my below code if I click show tab then it should show circle around item's location on a google map:
<div class="tab-pane" id="show">
<p>
<span class="heading_size">show:</span>
</p>
<p class="text-justify mb-0 pb-5">
<!-- <? php echo strtolower($data['item']->item_address); ?> -->
<div id="map" style="width:100%;height:500px"></div>
<script>
function myMap() {
var amsterdam = new google.maps.LatLng(52.395715,4.888916);
var mapCanvas = document.getElementById("map");
var mapOptions = {center: amsterdam, zoom: 7};
var map = new google.maps.Map(mapCanvas,mapOptions);
var myCity = new google.maps.Circle({
center: amsterdam,
radius: 50000,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.4
});
myCity.setMap(map);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=myMap"></script>
</p>
</div>
Problem Statement:
Below is the item details that gets printed out when I print item_address as shown in the above code (commented at this moment) using echo. So I need to use below data to make a circle around city field in the below json. For example: in the below json - city field is ottawa so it should make circle around ottawa city. As of now I can make circle around a particular lat/long but instead if I have a city name, then how can I make a circle around that city? Is this possible to do?
{
"address_id": 115,
"country": "canada",
"state": "ontario",
"city": "ottawa",
"street": "riverside drive",
"number": "1750",
"postal": "k1g 3t6"
}
You need to use Gecoding to find out position of city on the map. You can take a look at working example below.
I have created following function which allows you to draw circle around any city that you pass to the function:
google.maps.event.addDomListener(window, "load", function() {
myMap();
});
function myMap() {
//add global geocoder
window.geocoder = new google.maps.Geocoder();
var mapCanvas = document.getElementById("map_div");
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(33.808678, -117.918921)
};
window.map = new google.maps.Map(mapCanvas, mapOptions);
drawCircleAroundCity('ottawa');
}
function drawCircleAroundCity(cityName) {
if (!cityName) return;
if (!window.geocoder) throw "Geocoder is not loaded";
window.geocoder.geocode({
'address': cityName
}, function(results, status) {
if (status == 'OK') {
addCircle(results[0].geometry.location, true);
} else {
throw 'Unable to find address: ' + address;
}
});
}
function addCircle(position, recenter) {
if (typeof(position) != 'object') return;
if (!window.map) throw "Map is not loaded";
var myCity = new google.maps.Circle({
center: position,
radius: 50000,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.4
});
myCity.setMap(window.map);
if (recenter)
window.map.setCenter(position);
}
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
<div id="map_div" style="height: 400px;"></div>
Use the Google Maps Geocoding API and construct the appropriate request from your JSON fields. The API will return a JSON object containing the the latitude and longitude values.
Your API request will be in the form of:
https://maps.googleapis.com/maps/api/geocode/json?address=1750+riverside+drive,ottawa,ontario,canada&key=YOUR_API_KEY
Translating a city to LatLon can't be too hard but here's some code I could copy blindly without thinking too much. HTH.
var circleOptions = {
clickable: true,
draggable: true,
editable: true,
visible: false,
strokeColor: 'gray',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: 'gray',
fillOpacity: 0.35,
center: marker.getPosition()
};
radarCircle = new radarView(new google.maps.Circle(circleOptions));
google.maps.event.addDomListener(radarCircle, 'center_changed', reScope);
google.maps.event.addDomListener(radarCircle, 'radius_changed', reScope);
function radarView(superBase)
{
this.__proto__ = superBase;
if (this instanceof google.maps.Circle) {
augmentCircle.apply(this);
} else if (this instanceof google.maps.Rectangle) {
augmentRectangle.apply(this);
} else {
Tier3Toolbox.reportError({header:"Internal error",
message:"Inheriting from unknown object"});
}
this.doX = function(x){return "x is>" + x;};
return this;
}
function augmentCircle()
{
this.moveBorder = function()
{
google.maps.event.trigger(radarCircle,"center_changed");
}
}
function augmentRectangle()
{
this.moveBorder = function()
{
google.maps.event.trigger(radarRectangle,"bounds_changed");
}
}
function reScope() {
var searchReq = {'cmd':'search', 'scopeVintage':scopeVintage};
if (radarShape.getCenter) {
searchReq.checker = 0;
var currCenter = radarCircle.getCenter();
searchReq.centerLat = currCenter.lat();
searchReq.centerLng = currCenter.lng();
searchReq.radius = radarCircle.getRadius();
} else {
searchReq.checker = 1;
searchReq.SWLat = radarShape.getBounds().getSouthWest().lat();
searchReq.SWLng = radarShape.getBounds().getSouthWest().lng();
searchReq.NELat = radarShape.getBounds().getNorthEast().lat();
searchReq.NELng = radarShape.getBounds().getNorthEast().lng();
}
facFinder.postMessage(searchReq);
}

Google Maps JavaScript API - Create Polygon from Polylines Snapped to Road

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>

Categories