Rendering routes with GoogleAPI JS - javascript

I was following along with a tutorial involving the GoogleMaps API JS, and everything went well. When trying to building my own app I've come across an issue with displaying a route. The application I'm working on is mainly written in ruby on rails.
The "pseudo code" problem is when clicking on to "view route" button, the route is not displaying on the map.
Below is the HTML that triggers the first event when clicking on the search with in time button, and the CSS as requested.
<body>
<div>
<span class="text"> Within </span>
<select id='max-duration'>
<option value="10">10 min</option>
</select>
<select id="mode">
<option value="DRIVING">drive</option>
</select>
<span class="text">of</span>
<input id= 'search-within-time-text' type='text' placeholder='Your Location'>
<input id= 'search-within-time' type='button' value='Go'>
</div>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places,drawing,geometry&key=<%= ENV["MAP_API"] %>&v=3"></script>
</body>
<style>
#map {
bottom: 0px;
height: 500px;
left: 362px;
position: absolute;
right: 0px;
}
.container {
height: 500px;
position: relative;
}
.options-box {
background: #fff;
border: 1px solid black;
height: 91.75%;
line-height: 35px;
padding: 10px 10px 30px 10px;
text-align: left;
width: 340px;
}
#zoom-to-area-text{
width:200px;
}
</style>
The location array that is stroing the data is found in the maps controller, where we are pushing data from our SQLite DB.
def index
#test_array = []
#test.each do |h|
#test_array.push({lat: h.lat, lng: h.lng})
end
end
In particular I believe the problem lays within the function displayDirections. Which can be found at the bottom of the full code
The displayDirections function is written outside of the initMap function, because of a scoping issue when it is written inside of the initMap function. I've read the problem below
Maybe a similar issue
But had issues with displayDirections being defined at the click event, when it was written with in the initMap function, in the function displayMarkersWithinTime.
Any help is appreciated! Thanks!
function initMap() {
var map;
var markers = [];
var placeMarkers = [];
document.getElementById('search-within-time').addEventListener('click', function(){
searchWithinTime();
});
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 39.9523789, lng: -75.1635996},
zoom: 13,
mapTypeControl: false
});
var locations = <%= raw #test_array.to_json%>
for (var i = 0; i < locations.length; i++) {
var position = locations[i]
var marker = new google.maps.Marker({
position: position,
animation: google.maps.Animation.DROP,
id: i
});
markers.push(marker);
}
function hideMarkers(markers) {
for (var i = 0; i < markers.length; i++){
markers[i].setMap(null);
}
}
function searchWithinTime(){
var distanceMatrixService = new google.maps.DistanceMatrixService;
var address = document.getElementById('search-within-time-text').value;
if (address == ''){
window.alert('You must enter an address.');
} else {
hideMarkers(markers);
var origins = [];
for (var i = 0; i < markers.length; i++) {
origins[i] = markers[i].position;
}
var destination = address;
var mode = document.getElementById('mode').value;
distanceMatrixService.getDistanceMatrix({
origins: origins,
destinations: [destination],
travelMode: google.maps.TravelMode[mode],
unitSystem: google.maps.UnitSystem.IMPERIAL,
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
window.alert('Error was: ' + status);
} else {
displayMarkersWithinTime(response);
}
});
}
}
function displayMarkersWithinTime(response){
var maxDuration = document.getElementById('max-duration').value;
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var atLeastOne = false;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
if (element.status === "OK") {
var distanceText = element.distance.text;
var duration = element.duration.value / 60;
var durationText = element.duration.text;
if (duration <= maxDuration) {
markers[i].setMap(map);
atLeastOne = true;
var infowindow = new google.maps.InfoWindow({
content : durationText + ' away, ' + distanceText + '<div><input type=\"button\" value=\"View Route\" onclick =' + '\"displayDirections("' + origins[i] + '");\"</input></div>'
});
infowindow.open(map, markers[i]);
// if user clicks on marker close the small info window to open a new
markers[i].infowindow = infowindow;
google.maps.event.addListener(markers[i], 'click', function (){
this.infowindow.close();
});
}
}
}
}
if(!atLeastOne) {
window.alert('We could not find any locations within that distance');
}
console.log("hello")
}
}
var map;
var markers = [];
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 39.9523789, lng: -75.1635996},
zoom: 13,
mapTypeControl: false
});
function hideMarkers(markers) {
for (var i = 0; i < markers.length; i++){
markers[i].setMap(null);
}
}
function displayDirections(origin) {
hideMarkers(markers);
var directionsService = new google.maps.DirectionsService;
var destinationAddress = document.getElementById('search-within-time-text').value;
var mode = document.getElementById('mode').value;
directionsService.route({
origin: origin,
destination: destinationAddress,
travelMode: google.maps.TravelMode[mode]
}, function(response, status) {
console.log(response)
console.log(status)
if (status === google.maps.DirectionsStatus.OK) {
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
directions: response,
draggable: true,
polylineOptions: {
strokeColor: 'black'
}
}, console.log(map), console.log(response));
} else {
window.alert('Directions request failed due to ' + status);
}
});
console.log("testing")
}
google.maps.event.addDomListener(window, initMap())

Your (initialized) map variable is local to the initMap function. Make it global.
Change:
function initMap() {
var map;
// ...
To:
var map;
function initMap() {
proof of concept fiddle
code snippet:
var map;
function initMap() {
var markers = [];
var placeMarkers = [];
var titles;
var latitudes;
var longitudes;
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
document.getElementById('show-listings').addEventListener('click', showListings);
document.getElementById('hide-listings').addEventListener('click', function() {
hideMarkers(markers);
});
document.getElementById('search-within-time').addEventListener('click', function() {
searchWithinTime();
});
var timeAutocomplete = new google.maps.places.Autocomplete(
document.getElementById('search-within-time-text'));
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 39.9523789,
lng: -75.1635996
},
zoom: 13,
mapTypeControl: false
});
var locations = [{
lat: 39.952584,
lng: -75.165222
}, {
lat: 47.6062095,
lng: -122.3320708
},
{
lat: 34.0522342,
lng: -118.2436849
},
{
lat: 39.114053,
lng: -94.6274636
}, {
lat: 25.7616798,
lng: -80.1917902
}
];
for (var i = 0; i < locations.length; i++) {
var position = locations[i]
var marker = new google.maps.Marker({
position: position,
animation: google.maps.Animation.DROP,
id: i,
map: map
});
markers.push(marker);
}
function showListings() {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
bounds.extend(markers[i].position);
}
map.fitBounds(bounds);
}
function hideMarkers(markers) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
function searchWithinTime() {
var distanceMatrixService = new google.maps.DistanceMatrixService();
var address = document.getElementById('search-within-time-text').value;
if (address == '') {
window.alert('You must enter an address.');
} else {
hideMarkers(markers);
var origins = [];
for (var i = 0; i < markers.length; i++) {
origins[i] = markers[i].position;
}
var destination = address;
var mode = document.getElementById('mode').value;
distanceMatrixService.getDistanceMatrix({
origins: origins,
destinations: [destination],
travelMode: google.maps.TravelMode[mode],
unitSystem: google.maps.UnitSystem.IMPERIAL,
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
window.alert('Error was: ' + status);
} else {
displayMarkersWithinTime(response);
}
});
}
}
function displayMarkersWithinTime(response) {
var maxDuration = document.getElementById('max-duration').value;
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var atLeastOne = false;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
if (element.status === "OK") {
var distanceText = element.distance.text;
var duration = element.duration.value / 60;
var durationText = element.duration.text;
if (duration <= maxDuration) {
markers[i].setMap(map);
atLeastOne = true;
var infowindow = new google.maps.InfoWindow({
content: durationText + ' away, ' + distanceText + '<div><input type=\"button\" value=\"View Route\" onclick =' + '\"displayDirections("' + origins[i] + '");\"</input></div>'
});
infowindow.open(map, markers[i]);
// if user clicks on marker close the small info window to open a new
markers[i].infowindow = infowindow;
google.maps.event.addListener(markers[i], 'click', function() {
this.infowindow.close();
});
}
}
}
}
if (!atLeastOne) {
window.alert('We could not find any locations within that distance');
}
console.log("hello")
}
}
var map;
var markers = [];
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 39.9523789,
lng: -75.1635996
},
zoom: 13,
mapTypeControl: false
});
function hideMarkers(markers) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
function displayDirections(origin) {
hideMarkers(markers);
var directionsService = new google.maps.DirectionsService();
var destinationAddress = document.getElementById('search-within-time-text').value;
var mode = document.getElementById('mode').value;
directionsService.route({
origin: origin,
destination: destinationAddress,
travelMode: google.maps.TravelMode[mode]
}, function(response, status) {
console.log(response)
console.log(status)
if (status === google.maps.DirectionsStatus.OK) {
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
directions: response,
draggable: true,
polylineOptions: {
strokeColor: 'black'
}
}, console.log(map), console.log(response));
} else {
window.alert('Directions request failed due to ' + status);
}
});
console.log("testing")
}
google.maps.event.addDomListener(window, 'load', initMap)
html,
body,
#map {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
background-color: white;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input type="button" value="search" id="search-within-time" />
<input type="text" value="coffee" id="search-within-time-text" />
<input type="button" value="Show" id="show-listings" />
<input type="button" value="Hide" id="hide-listings" />
<input type="text" value="DRIVING" id="mode" />
<input type="text" value="1200" id="max-duration" />
<div id="map"></div>

Related

How to load the correct KML according to location?

I have 15 kml files and I have a map from google map api, still I haven't found some way to put the correct kml from 15 kml files that I have according if the location are within kml area. Its possible to do that?
Example: I have this kml file in my map but if i am in other location but within kml area how can i check this one new coordinate is within the kml area?
One try that i made was extract 'sublocality' from my responde and in array put all sublocalitys from this area, the problem for this i the quantityt form each districts (like 80 subocalities each kml)
geocoder.geocode(
{'location': latlng},
function(results, status) {
if (status === 'OK') {
for (var i = 0; i < results[0].address_components.length; i++){
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
for (var i = 0; i < results.length; i++) {
//alert(results[i].types[0]+','+results[i].types[1]+','+results[i].address_components[0].long_name)
//district how i get them
if (results[i].types[0]=='political' && results[i].types[1]=='sublocality' ){
district = results[i].address_components[0].long_name;
console.log("Estas en el distrito: " + district);
console.log(district);
console.log(results);
}
}
}
else {console.log("No reverse geocode results.")}
}
else {console.log("Geocoder failed: " + status)}
}
}});
/*For get district*/
var distrito_2=["Peublito","San Jose 2","Independencia"];
var src_aux=null;
for(var i=0; i<distrito_1.length; i++){
if(district==distrito_1[i]){
console.log(distrito_1[i] + " Estas en el Distrito 1");
src_aux='https://www.dropbox.com/s/u8knmtfsp4bhnkd/Distrito_1.kml?dl=1';
}
}
for(var j=0; j<distrito_2.length; j++){
if(district==distrito_2[j]){
console.log(distrito_2[j] + " Estas en el Distrito 4");
src_aux='https://www.dropbox.com/s/e3t3u4y3ytxgkj1/Distrito_4.kml?dl=1';
}
}
var src=src_aux;
var kmlLayer = new google.maps.KmlLayer(src, {
suppressInfoWindows: true,
preserveViewport: false,
map: map
});
One option is something like this example
This is implemented using the geoxml3 library to parse the KML to native Google Maps Javascript API v3 objects, then process through them to determine if the point is in one of the polygons, then show that KML, hiding all others
(disclaimer, I maintain that library)
proof of concept fiddle (only one polygon from each KML)
code snippet:
var geoXml = null;
var map = null;
var geocoder = null;
var toggleState = 1;
var infowindow = null;
var marker = null;
var address = null;
function initialize() {
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: 20.644352,
lng: -100.415056
},
zoom: 13,
});
geoXml = new geoXML3.parser({
map: map,
singleInfoWindow: true,
infoWindow: infowindow,
zoom: false
});
google.maps.event.addListener(geoXml, "parsed", function() {
if (address) setTimeout(function() {
showAddress(address);
}, 500);
});
geoXml.parseKmlString(Distrito_1_kml);
geoXml.parseKmlString(Distrito_4_kml);
google.maps.event.addListenerOnce(map, "idle", function() {
for (var j = 0; j < geoXml.docs.length; j++) {
for (var i = 0; i < geoXml.docs[j].placemarks.length; i++) {
var placemark = geoXml.docs[j].placemarks[i];
if (placemark.polygon) {
google.maps.event.addListener(placemark.polygon, 'click', clickHandler);
}
}
}
});
function clickHandler(evt) {
var contentString = "click<br>Outside Area";
var point = evt.latLng;
contentString += "<br>" + point.toUrlValue(6);
map.setCenter(point);
if (marker && marker.setMap) marker.setMap(null);
marker = new google.maps.Marker({
map: map,
position: point
});
contentString = findAndDisplayKml("click", point, contentString);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
google.maps.event.trigger(marker, "click");
}
}
function showAddress(address) {
var contentString = address + "<br>Outside Area";
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var point = results[0].geometry.location;
contentString += "<br>" + point;
map.setCenter(point);
if (marker && marker.setMap) marker.setMap(null);
marker = new google.maps.Marker({
map: map,
position: point
});
contentString = findAndDisplayKml(address, point, contentString);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
google.maps.event.trigger(marker, "click");
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function findAndDisplayKml(address, point, contentString) {
for (var j = 0; j < geoXml.docs.length; j++) {
geoXml.hideDocument(geoXml.docs[j]);
for (var i = 0; i < geoXml.docs[j].gpolygons.length; i++) {
if (google.maps.geometry.poly.containsLocation(point, geoXml.docs[j].gpolygons[i])) {
contentString = address + "<br>" + geoXml.docs[j].placemarks[i].name;
contentString += "<br>" + point + "<br>polygon#" + i;
geoXml.showDocument(geoXml.docs[j]);
}
}
}
return contentString;
}
window.initialize = initialize;
google.maps.event.addDomListener(window, 'load', initialize);
var Distrito_1_kml = '<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://www.opengis.net/kml/2.2"><Document><name>Distrito_1</name><Style id="poly-0288D1-2000-76-normal"><LineStyle><color>ffd18802</color><width>2</width></LineStyle><PolyStyle><color>4cd18802</color><fill>1</fill><outline>1</outline></PolyStyle></Style><Style id="poly-0288D1-2000-76-highlight"><LineStyle><color>ffd18802</color><width>3</width></LineStyle><PolyStyle><color>4cd18802</color><fill>1</fill><outline>1</outline></PolyStyle></Style><StyleMap id="poly-0288D1-2000-76"><Pair><key>normal</key><styleUrl>#poly-0288D1-2000-76-normal</styleUrl></Pair><Pair><key>highlight</key><styleUrl>#poly-0288D1-2000-76-highlight</styleUrl></Pair></StyleMap><Placemark><name>278</name><description><![CDATA[SECCIÓN: 278<br>ENTIDAD: Querétaro<br>MUNICIPIO: 14 - Santiago de Querétaro<br>DISTRITO LOCAL: 1]]></description><styleUrl>#poly-0288D1-2000-76</styleUrl><ExtendedData><Data name="SECCIÓN"><value>278</value></Data><Data name="ENTIDAD"><value>Querétaro</value></Data><Data name="MUNICIPIO"><value>14 - Santiago de Querétaro</value></Data><Data name="DISTRITO LOCAL"><value>1</value></Data></ExtendedData><Polygon><outerBoundaryIs><LinearRing><tessellate>1</tessellate><coordinates> -100.409668,20.629613,0 -100.409679,20.629712,0 -100.409677,20.630144,0 -100.409677,20.630171,0 -100.409736,20.630203,0 -100.40974,20.630463,0 -100.409766,20.631484,0 -100.408865,20.631579,0 -100.40774,20.631686,0 -100.406707,20.631787,0 -100.406284,20.631817,0 -100.406178,20.631825,0 -100.40615,20.631935,0 -100.406067,20.632246,0 -100.405943,20.632227,0 -100.40592,20.632289,0 -100.405889,20.632386,0 -100.405724,20.633048,0 -100.405695,20.633181,0 -100.405672,20.633451,0 -100.405676,20.633638,0 -100.4057,20.633793,0 -100.405738,20.633977,0 -100.405812,20.634262,0 -100.405874,20.634465,0 -100.405961,20.634735,0 -100.405996,20.634858,0 -100.406049,20.635118,0 -100.406072,20.635331,0 -100.406063,20.635521,0 -100.406045,20.635705,0 -100.406024,20.635952,0 -100.405983,20.636413,0 -100.40598,20.63645,0 -100.40595,20.636858,0 -100.405895,20.637401,0 -100.405889,20.637469,0 -100.40587,20.637762,0 -100.405842,20.638065,0 -100.405751,20.639173,0 -100.405732,20.639402,0 -100.405704,20.639709,0 -100.405628,20.640562,0 -100.405582,20.641011,0 -100.405564,20.641259,0 -100.405446,20.642328,0 -100.405318,20.643219,0 -100.405374,20.643227,0 -100.405399,20.643231,0 -100.405456,20.643239,0 -100.406037,20.643395,0 -100.406437,20.643468,0 -100.407015,20.64359,0 -100.40704,20.643685,0 -100.408085,20.643885,0 -100.409438,20.644105,0 -100.409939,20.644173,0 -100.409878,20.644563,0 -100.409818,20.644919,0 -100.409751,20.64538,0 -100.41022,20.645442,0 -100.41111,20.645431,0 -100.411504,20.645414,0 -100.412221,20.645394,0 -100.412427,20.645388,0 -100.412962,20.645388,0 -100.41305,20.645388,0 -100.413431,20.645386,0 -100.414645,20.645386,0 -100.415518,20.645369,0 -100.416074,20.645369,0 -100.416259,20.645391,0 -100.416281,20.646105,0 -100.416282,20.646274,0 -100.41605,20.648333,0 -100.416051,20.648501,0 -100.41727,20.648281,0 -100.41769,20.648367,0 -100.418161,20.648372,0 -100.418367,20.648374,0 -100.419087,20.648353,0 -100.419149,20.648262,0 -100.419288,20.648107,0 -100.419407,20.647987,0 -100.419611,20.647847,0 -100.41978,20.647777,0 -100.420391,20.647573,0 -100.420984,20.647497,0 -100.422092,20.647409,0 -100.424483,20.647507,0 -100.424309,20.647752,0 -100.424257,20.647935,0 -100.424227,20.648161,0 -100.424256,20.648305,0 -100.424305,20.648424,0 -100.424361,20.64856,0 -100.424457,20.648686,0 -100.424571,20.648801,0 -100.424734,20.648895,0 -100.424901,20.64899,0 -100.425074,20.649078,0 -100.425298,20.649134,0 -100.425556,20.649144,0 -100.425808,20.649116,0 -100.426017,20.64907,0 -100.426157,20.649002,0 -100.426322,20.648911,0 -100.426478,20.64881,0 -100.426633,20.648699,0 -100.42674,20.648567,0 -100.426825,20.648425,0 -100.426879,20.648276,0 -100.426909,20.648128,0 -100.426976,20.647611,0 -100.427061,20.647082,0 -100.427129,20.646682,0 -100.427177,20.646407,0 -100.427267,20.646006,0 -100.427389,20.645516,0 -100.427424,20.645349,0 -100.427566,20.644798,0 -100.427772,20.644361,0 -100.427917,20.644017,0 -100.428127,20.64377,0 -100.428267,20.643654,0 -100.428392,20.643547,0 -100.4285,20.643468,0 -100.428463,20.64357,0 -100.428438,20.643755,0 -100.428414,20.643993,0 -100.428422,20.644287,0 -100.428483,20.646538,0 -100.428548,20.649113,0 -100.42862,20.652588,0 -100.428633,20.652888,0 -100.428496,20.652953,0 -100.428183,20.652938,0 -100.427874,20.65296,0 -100.427573,20.653128,0 -100.427196,20.65325,0 -100.426666,20.653255,0 -100.42619,20.653591,0 -100.42584,20.653974,0 -100.42539,20.654381,0 -100.424962,20.654527,0 -100.424534,20.65465,0 -100.424082,20.654796,0 -100.421918,20.655855,0 -100.421962,20.656975,0 -100.42399,20.656872,0 -100.424178,20.656966,0 -100.424443,20.657054,0 -100.424708,20.657237,0 -100.424849,20.657355,0 -100.42493,20.657424,0 -100.424741,20.657959,0 -100.42454,20.658633,0 -100.423783,20.65966,0 -100.423629,20.660163,0 -100.423832,20.660401,0 -100.424282,20.661192,0 -100.424526,20.661691,0 -100.424871,20.662522,0 -100.425065,20.662688,0 -100.425891,20.663295,0 -100.426348,20.663612,0 -100.426923,20.663991,0 -100.427301,20.663709,0 -100.427383,20.663971,0 -100.427835,20.664538,0 -100.428085,20.664345,0 -100.428486,20.663879,0 -100.428889,20.663352,0 -100.429273,20.662799,0 -100.430088,20.662758,0 -100.430745,20.662683,0 -100.431194,20.662662,0 -100.43144,20.662651,0 -100.431967,20.662559,0 -100.432337,20.662451,0 -100.432465,20.662276,0 -100.432741,20.662077,0 -100.432827,20.662015,0 -100.432874,20.661981,0 -100.432824,20.661519,0 -100.432794,20.661265,0 -100.432722,20.66063,0 -100.432678,20.660225,0 -100.432622,20.659696,0 -100.43259,20.659398,0 -100.432569,20.659193,0 -100.4325,20.658553,0 -100.432471,20.658277,0 -100.432402,20.65765,0 -100.432359,20.657263,0 -100.43226,20.656375,0 -100.43216,20.655417,0 -100.43211,20.654995,0 -100.432048,20.65448,0 -100.432008,20.654025,0 -100.431916,20.653163,0 -100.431871,20.652729,0 -100.431801,20.652055,0 -100.431766,20.65171,0 -100.431701,20.651094,0 -100.431644,20.650602,0 -100.431541,20.649636,0 -100.43143,20.648652,0 -100.431375,20.648168,0 -100.43133,20.647664,0 -100.431298,20.647266,0 -100.431288,20.647142,0 -100.431281,20.647064,0 -100.43128,20.647045,0 -100.43127,20.646958,0 -100.431249,20.64678,0 -100.431246,20.646762,0 -100.431021,20.644856,0 -100.43101,20.644763,0 -100.430944,20.644197,0 -100.430865,20.643219,0 -100.430858,20.643095,0 -100.430855,20.643058,0 -100.430853,20.643017,0 -100.43081,20.642347,0 -100.430806,20.642283,0 -100.430804,20.642253,0 -100.4308,20.642197,0 -100.430797,20.642146,0 -100.430795,20.642117,0 -100.430793,20.642089,0 -100.430709,20.641467,0 -100.430668,20.641084,0 -100.430649,20.640904,0 -100.430644,20.640856,0 -100.430482,20.640176,0 -100.430299,20.639634,0 -100.42995,20.638893,0 -100.429937,20.638867,0 -100.429467,20.637874,0 -100.429077,20.637082,0 -100.428739,20.636372,0 -100.428481,20.635831,0 -100.427989,20.634822,0 -100.42776,20.634325,0 -100.427287,20.633299,0 -100.427198,20.633104,0 -100.426599,20.631688,0 -100.426416,20.631228,0 -100.426409,20.63121,0 -100.425877,20.629881,0 -100.425826,20.629755,0 -100.425815,20.629726,0 -100.425786,20.62965,0 -100.425422,20.628688,0 -100.425336,20.628494,0 -100.42525,20.6283,0 -100.424608,20.626793,0 -100.424455,20.626424,0 -100.423544,20.624231,0 -100.423324,20.623653,0 -100.423077,20.623005,0 -100.422868,20.622456,0 -100.422816,20.622325,0 -100.422801,20.622287,0 -100.42277,20.62221,0 -100.422432,20.622165,0 -100.42207,20.622108,0 -100.42132,20.621991,0 -100.420547,20.621882,0 -100.42039,20.62186,0 -100.419795,20.621778,0 -100.419674,20.621761,0 -100.419569,20.621747,0 -100.419549,20.621743,0 -100.419517,20.621738,0 -100.419429,20.621722,0 -100.41928,20.621696,0 -100.419197,20.621682,0 -100.418642,20.621585,0 -100.418609,20.621581,0 -100.418569,20.621576,0 -100.418475,20.621564,0 -100.417963,20.6215,0 -100.417891,20.621491,0 -100.417835,20.621484,0 -100.41776,20.621471,0 -100.417643,20.621452,0 -100.417184,20.621376,0 -100.41716,20.621372,0 -100.416811,20.621313,0 -100.416738,20.621302,0 -100.416712,20.621472,0 -100.417641,20.621598,0 -100.418602,20.621763,0 -100.418722,20.622057,0 -100.41787,20.622215,0 -100.418221,20.623157,0 -100.418466,20.623771,0 -100.41836,20.623797,0 -100.418067,20.623868,0 -100.41759,20.623966,0 -100.417702,20.62427,0 -100.417844,20.624656,0 -100.417312,20.624797,0 -100.417357,20.625136,0 -100.417388,20.625471,0 -100.41742,20.625469,0 -100.417734,20.625446,0 -100.418001,20.625418,0 -100.418268,20.625389,0 -100.41831,20.625836,0 -100.418314,20.625884,0 -100.418341,20.626164,0 -100.418372,20.626364,0 -100.418405,20.626574,0 -100.418424,20.626726,0 -100.418436,20.626825,0 -100.418463,20.626916,0 -100.418484,20.626983,0 -100.418588,20.627132,0 -100.418763,20.627254,0 -100.418909,20.627385,0 -100.418941,20.627425,0 -100.419004,20.627503,0 -100.419048,20.627679,0 -100.419063,20.627833,0 -100.419027,20.627957,0 -100.41892,20.628068,0 -100.418668,20.628094,0 -100.418495,20.628112,0 -100.418222,20.628141,0 -100.417921,20.628172,0 -100.4177,20.628195,0 -100.41773,20.628435,0 -100.416789,20.628549,0 -100.416545,20.628577,0 -100.416156,20.62862,0 -100.415776,20.628663,0 -100.41539,20.628706,0 -100.415005,20.628749,0 -100.414648,20.628789,0 -100.414655,20.629057,0 -100.41466,20.629217,0 -100.414663,20.629376,0 -100.413013,20.629444,0 -100.412907,20.628874,0 -100.412831,20.628879,0 -100.412811,20.628881,0 -100.412802,20.628818,0 -100.412744,20.628826,0 -100.412641,20.62884,0 -100.412229,20.628887,0 -100.412207,20.62889,0 -100.412109,20.628901,0 -100.412067,20.628906,0 -100.411789,20.628938,0 -100.411767,20.62894,0 -100.411679,20.62895,0 -100.411642,20.628954,0 -100.411394,20.628983,0 -100.411326,20.628991,0 -100.411107,20.629016,0 -100.410991,20.629029,0 -100.410692,20.6295,0 -100.41041,20.629968,0 -100.410392,20.629997,0 -100.409668,20.629613,0</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark></Document></kml>';
var Distrito_4_kml = '<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://www.opengis.net/kml/2.2"><Document><name>Distrito_4</name><Style id="poly-817717-2000-76-normal"><LineStyle><color>ff177781</color><width>2</width></LineStyle><PolyStyle><color>4c177781</color><fill>1</fill><outline>1</outline></PolyStyle></Style><Style id="poly-817717-2000-76-highlight"><LineStyle><color>ff177781</color><width>3</width></LineStyle><PolyStyle><color>4c177781</color><fill>1</fill><outline>1</outline></PolyStyle></Style><StyleMap id="poly-817717-2000-76"><Pair><key>normal</key><styleUrl>#poly-817717-2000-76-normal</styleUrl></Pair><Pair><key>highlight</key><styleUrl>#poly-817717-2000-76-highlight</styleUrl></Pair></StyleMap><Placemark><name>873</name><description><![CDATA[SECCIÓN: 873<br>ENTIDAD: Querétaro<br>DISTRITO LOCAL: 4<br>MUNICIPIO: 14 - Querétaro]]></description><styleUrl>#poly-817717-2000-76</styleUrl><ExtendedData><Data name="SECCIÓN"><value>873</value></Data><Data name="ENTIDAD"><value>Querétaro</value></Data><Data name="DISTRITO LOCAL"><value>4</value></Data><Data name="MUNICIPIO"><value>14 - Querétaro</value></Data></ExtendedData><Polygon><outerBoundaryIs><LinearRing><tessellate>1</tessellate><coordinates> -100.387018,20.653116,0 -100.387013,20.653004,0 -100.387008,20.652893,0 -100.386972,20.652406,0 -100.386918,20.651922,0 -100.386901,20.651777,0 -100.386856,20.651331,0 -100.386808,20.650925,0 -100.387001,20.650915,0 -100.38741,20.650885,0 -100.387892,20.650845,0 -100.387829,20.650077,0 -100.387819,20.649967,0 -100.387802,20.649779,0 -100.38775,20.64929,0 -100.387733,20.64913,0 -100.387688,20.64866,0 -100.387633,20.648093,0 -100.387427,20.64801,0 -100.38727,20.648222,0 -100.387047,20.648519,0 -100.386905,20.648699,0 -100.386793,20.648818,0 -100.386505,20.648618,0 -100.386161,20.648394,0 -100.385745,20.648144,0 -100.385368,20.647898,0 -100.385093,20.647712,0 -100.384971,20.647704,0 -100.38459,20.647692,0 -100.384169,20.647704,0 -100.383771,20.647707,0 -100.383534,20.647697,0 -100.383451,20.647725,0 -100.383356,20.64777,0 -100.383355,20.647705,0 -100.38272,20.647289,0 -100.382523,20.64716,0 -100.382382,20.647069,0 -100.382193,20.647327,0 -100.38218,20.647254,0 -100.381338,20.64651,0 -100.380943,20.646118,0 -100.380487,20.64562,0 -100.380335,20.645467,0 -100.380254,20.645587,0 -100.38013,20.645799,0 -100.380038,20.645948,0 -100.379893,20.646355,0 -100.379787,20.646673,0 -100.379565,20.647378,0 -100.379476,20.647649,0 -100.379344,20.64806,0 -100.379083,20.648925,0 -100.378938,20.649367,0 -100.37882,20.64977,0 -100.378679,20.650227,0 -100.378551,20.650662,0 -100.377934,20.652708,0 -100.377661,20.653563,0 -100.377527,20.65398,0 -100.377504,20.654161,0 -100.377618,20.654096,0 -100.378376,20.653822,0 -100.379451,20.653702,0 -100.380207,20.653642,0 -100.3805,20.65362,0 -100.380805,20.653597,0 -100.380867,20.653593,0 -100.381008,20.653582,0 -100.381346,20.653557,0 -100.381679,20.653531,0 -100.382206,20.653506,0 -100.382744,20.653452,0 -100.382803,20.653448,0 -100.383057,20.65343,0 -100.383387,20.653405,0 -100.383713,20.65338,0 -100.383815,20.653372,0 -100.38476,20.653302,0 -100.384882,20.653291,0 -100.385975,20.653201,0 -100.387018,20.653116,0</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark></Document></kml>';
#map {
height: 70%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
</head>
<body>
<form action="#" onsubmit="showAddress(this.address.value); return false" style="padding:10px 0px 30px 0px; background:none;">
<p>
<label>Address Search</label><br/>
<input type="text" size="60" id="address" name="address" value="San Jose El Alto" class="address" /><br/>
<input type="submit" value="Search" />(options: San Jose El Alto, Vistas de San Pablo)
</p>
</form>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/geocodezip/geoxml3#master/polys/geoxml3.js"></script>
</body>
</html>

How to make mixed path road type? (snap to roads and simple polyline) Google Maps API

I need to draw the path, but the road has the flights on the way. So I want to make something like in my example, but I need to draw it on page init instant of a manual. But I don't know how to mix this two ways to draw maps (Polilyne and Snap to roads). It needs to works from an array of lat lng like that:
var points = new google.maps.MVCArray([
new google.maps.LatLng(39.9042, 116.407396),
new google.maps.LatLng(34.341574, 108.93977),
new google.maps.LatLng(31.23039, 121.473702),
new google.maps.LatLng(31.298974, 120.585289),
new google.maps.LatLng(30.274084, 120.15507),
new google.maps.LatLng(25.234479, 110.179953),
new google.maps.LatLng(23.12911, 113.264385),
new google.maps.LatLng(22.543096, 114.057865),
new google.maps.LatLng(22.279991, 114.158798)
]);
Here is my code:
If you click on the map it draws the snap to roads path and if you hold the Shift key and click it will draw the polyline.
I need somehow update the code to make if lat lng return ZERO_RESULTS for the snap roads resume the road drawing with polyline like in my code example.
Here is the what I want to make:
map example
Thanks for your help
var map, path = new google.maps.MVCArray(),
service = new google.maps.DirectionsService(),
shiftPressed = false,
poly;
google.maps.event.addDomListener(document, "keydown", function(e) {
shiftPressed = e.shiftKey;
});
google.maps.event.addDomListener(document, "keyup", function(e) {
shiftPressed = e.shiftKey;
});
function Init() {
var myOptions = {
zoom: 17,
center: new google.maps.LatLng(37.2008385157313, -93.2812106609344),
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE]
},
disableDoubleClickZoom: true,
scrollwheel: false,
draggableCursor: "crosshair"
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
poly = new google.maps.Polyline({
map: map
});
google.maps.event.addListener(map, "click", function(evt) {
if (shiftPressed || path.getLength() === 0) {
path.push(evt.latLng);
if (path.getLength() === 1) {
poly.setPath(path);
}
} else {
service.route({
origin: path.getAt(path.getLength() - 1),
destination: evt.latLng,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
});
}
html,
body {
margin: 0;
width: 100%;
height: 100%;
}
#map_canvas {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
<body onload="Init()">
<div id="map_canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBjkJC-gvn3j6T3gvd3aE2vbUS5qTEhi5s"></script>
</body>
If the directions request fails, add the clicked point to your polyline.
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
} else {
console.log("directions request failed:"+status);
// add point to polyline (makes a straight line segment
path.push(evt.latLng);
}
code snippet:
var map, path = new google.maps.MVCArray(),
service = new google.maps.DirectionsService(),
shiftPressed = false,
poly;
google.maps.event.addDomListener(document, "keydown", function(e) {
shiftPressed = e.shiftKey;
});
google.maps.event.addDomListener(document, "keyup", function(e) {
shiftPressed = e.shiftKey;
});
function Init() {
var myOptions = {
zoom: 7,
center: new google.maps.LatLng(37.2008385157313, -93.2812106609344),
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE]
},
disableDoubleClickZoom: true,
scrollwheel: false,
draggableCursor: "crosshair"
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
poly = new google.maps.Polyline({
map: map
});
google.maps.event.addListener(map, "click", function(evt) {
if (shiftPressed || path.getLength() === 0) {
path.push(evt.latLng);
if (path.getLength() === 1) {
poly.setPath(path);
}
} else {
service.route({
origin: path.getAt(path.getLength() - 1),
destination: evt.latLng,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
} else {
console.log("directions request failed:" + status);
// create polyline
path.push(evt.latLng);
}
});
}
});
}
html,
body {
margin: 0;
width: 100%;
height: 100%;
}
#map_canvas {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
<body onload="Init()">
<div id="map_canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBjkJC-gvn3j6T3gvd3aE2vbUS5qTEhi5s"></script>
</body>
Here it was what I needed, thanks all for the help!
Code example:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Polylines</title>
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initialize() {
var pos = new google.maps.LatLng(47.229808, -1.560401);
var myOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var bounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById('map'), myOptions);
var service = new google.maps.DirectionsService();
var path = [];
var cur = 1;
var trip = [
new google.maps.LatLng(22.396428,114.109497),
new google.maps.LatLng(13.756331,100.501765),
new google.maps.LatLng(1.352083,103.819836),
new google.maps.LatLng(-6.17511,106.865039),
new google.maps.LatLng(-6.917464,107.619123),
new google.maps.LatLng(-7.79558,110.36949),
new google.maps.LatLng(-8.409518,115.188916),
new google.maps.LatLng(22.396428,114.109497),
];
var poly = new google.maps.Polyline({
strokeColor: "blue",
strokeOpacity: 1.0,
strokeWeight: 2
});
function build() {
if (!trip[cur] || !trip[cur - 1]) {
// build map
poly.setPath(path);
map.fitBounds(bounds);
return;
}
bounds.extend(trip[cur]);
service.route({
origin: trip[cur - 1],
destination: trip[cur],
travelMode: google.maps.DirectionsTravelMode.DRIVING
},
function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
} else {
path.push(trip[cur]);
}
cur++;
build();
});
}
bounds.extend(trip[0]);
build();
poly.setMap(map);
};
window.onload = function() {
initialize();
};
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBjkJC-gvn3j6T3gvd3aE2vbUS5qTEhi5s">
</script>
</body>
</html>

Change the color between waypoints and fit the route to moved map marker

I use the google maps api to draw a route in a embedded google map. I changed the color of the hole route but I also would like to change the color between the waypoints for example:
Start --orange--> firstWP --red-- > secondWP --orange--> firstWP --red--> secondWp --orange--> Destination
The color between firstWP to seceondWP should be changed but secondWP to FirstWP sould be the same color as the other parts of the route.
Furthermore I also need to move the map markers and the route should move/change
fitting to the new position of the map marker but keep the different color.
This is a minimal example with draggable map marker and changed color between waypoints but the route does not adapt to the new position of the map markers
var map;
var directionsService;
var directionsDisplay;
function initialize() {
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
});
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
suppressPolylines: true
});
calcRoute(39.2903848, -76.6121893, 42.3600825, -71.05888);
}
google.maps.event.addDomListener(window, "load", initialize);
function calcRoute(origin_lat, origin_lng, destination_lat, destination_lng) {
console.log("Entrée CALC ROUTE");
var origin = new google.maps.LatLng(origin_lat, origin_lng);
var destination = new google.maps.LatLng(destination_lat, destination_lng);
var waypointsArray = document.getElementById('waypoints').value.split("|");
var waypts = [];
for (i = 0; i < waypointsArray.length; i++) {
if (waypointsArray[i] != "") {
var waypoint = waypointsArray[i];
var waypointArray = waypoint.split(",");
var waypointLat = waypointArray[0];
var waypointLng = waypointArray[1];
console.log("waypts lat " + waypointLat);
console.log("waypts lng " + waypointLng);
waypts.push({
location: new google.maps.LatLng(waypointLat, waypointLng),
stopover: true
})
}
}
console.log("waypts " + waypts.length);
var request = {
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
waypoints: waypts,
provideRouteAlternatives: true
};
console.log("Calc request " + JSON.stringify(request));
directionsService.route(request, customDirectionsRenderer);
}
function customDirectionsRenderer(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var polyline = new google.maps.Polyline({map:map, strokeColor: "blue", path:[]})
if (i == 1) {
polyline.setOptions({strokeColor: "red"});
}
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
map.fitBounds(bounds);
}
};
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
<input id="waypoints" value="39.9525839,-75.1652215|40.7127837,-74.0059413" />
<div id="map_canvas"></div>
http://jsfiddle.net/westify/vop9o1n5/1/
Is it possible to do that? Or is it only possible if rerender the whole route after moved one waypoint?
One option would be to listen for the directions_changed event on the DirectionsRenderer, when that fires, redraw the directions polylines.
var firstTime = true;
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
console.log("directions changed firstTime=" + firstTime);
// prevent infinite loop
if (firstTime) {
google.maps.event.addListenerOnce(directionsDisplay, 'directions_changed', function() {
console.log("directions changed");
customDirectionsRenderer(directionsDisplay.getDirections(), "OK");
});
}
firstTime = !firstTime;
});
proof of concept fiddle
code snippet:
var map;
var directionsService;
var directionsDisplay;
var firstTime = true;
function initialize() {
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
});
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
suppressPolylines: true
});
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
console.log("directions changed firstTime=" + firstTime);
if (firstTime) {
google.maps.event.addListenerOnce(directionsDisplay, 'directions_changed', function() {
console.log("directions changed"); //+JSON.stringify(directionsDisplay.getDirections()));
customDirectionsRenderer(directionsDisplay.getDirections(), "OK");
});
}
firstTime = !firstTime;
});
calcRoute(39.2903848, -76.6121893, 42.3600825, -71.05888);
}
google.maps.event.addDomListener(window, "load", initialize);
function calcRoute(origin_lat, origin_lng, destination_lat, destination_lng) {
console.log("Entrée CALC ROUTE");
var origin = new google.maps.LatLng(origin_lat, origin_lng);
var destination = new google.maps.LatLng(destination_lat, destination_lng);
var waypointsArray = document.getElementById('waypoints').value.split("|");
var waypts = [];
for (i = 0; i < waypointsArray.length; i++) {
if (waypointsArray[i] != "") {
var waypoint = waypointsArray[i];
var waypointArray = waypoint.split(",");
var waypointLat = waypointArray[0];
var waypointLng = waypointArray[1];
console.log("waypts lat " + waypointLat);
console.log("waypts lng " + waypointLng);
waypts.push({
location: new google.maps.LatLng(waypointLat, waypointLng),
stopover: true
})
}
}
console.log("waypts " + waypts.length);
var request = {
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
waypoints: waypts,
provideRouteAlternatives: true
};
console.log("Calc request " + JSON.stringify(request));
directionsService.route(request, customDirectionsRenderer);
}
var polylines = [];
function customDirectionsRenderer(response, status) {
for (var i = 0; i < polylines.length; i++) {
polylines[i].setMap(null);
}
polylines = [];
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var polyline = new google.maps.Polyline({
map: map,
strokeColor: "blue",
path: []
});
polylines.push(polyline);
if (i == 1) {
polyline.setOptions({
strokeColor: "red"
});
}
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
map.fitBounds(bounds);
}
};
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="waypoints" value="39.9525839,-75.1652215|40.7127837,-74.0059413" />
<div id="map_canvas"></div>

JS Geocoder cannot assign Global Variable for Google Maps Variable

i have variable array 2 dimentional:
var locations = new Array(3);
for (var i = 0; i < 3; i++) {
locations[i] = ['1', '2', '3'];
}
and i have array with name Place inside
data = ["Terogong, Indonesia", "Blok M, Indonesia", "Cipinang, Indonesia"]
when i use Geocoder to search Lat and Lang, then its fill Locations[] with name place, Lat and Lang:
for (var i = 0; i < data.length-1; i++) {
var c = data[i];
geocoder.geocode( { 'address': data[i] + ", indonesia"}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//alert("location : " + results[0].geometry.location.lat() + " " +results[0].geometry.location.lng());
locations[i] = [c , results[0].geometry.location.lat(), results[0].geometry.location.lng()];
alert(locations[i]);
} else {
alert("Something got wrong " + status);
}
});
}
and then, when i alert(locations[0]) its apear 1.
why this is happen??
The geocoder is asynchronous. One option is to use function closure to associate the variables in the request with the callback function:
for (var i = 0; i < data.length; i++) {
geocoder.geocode({
'address': data[i] + ", indonesia"
}, (function(data, i) { return function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
locations[i] = [data, results[0].geometry.location.lat(), results[0].geometry.location.lng()];
var mark = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: data
});
// alert(locations[i]);
} else {
alert("Something got wrong " + status);
}
}}(data[i], i))); // has function closure on data[i] as data, i (as i)
}
working fiddle
code snippet:
var geocoder = new google.maps.Geocoder();
var map;
var data = ["Terogong, Indonesia", "Blok M, Indonesia", "Cipinang, Indonesia"];
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
});
var bounds = new google.maps.LatLngBounds();
var locations = new Array(3);
for (var i = 0; i < 3; i++) {
locations[i] = ['1', '2', '3'];
}
for (var i = 0; i < data.length; i++) {
geocoder.geocode({
'address': data[i] + ", indonesia"
}, (function(data, i) {
return function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
locations[i] = [data, results[0].geometry.location.lat(), results[0].geometry.location.lng()];
var mark = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: data
});
} else {
alert("Something got wrong " + status);
}
}
}(data[i], i)));
}
}
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"></script>
<div id="map_canvas"></div>

Show alert when route crosses polygon in google maps, no markers near the polygon

I hope you all are doing just fine.
I have a little problem when creating a route on google maps:
I create polygons dinamically from information stored in a database and I want an alert to be shown when the route I create passes by the polygon.
The problem is that no markers are generated inside the polygon, therefore no alert is shown, so I want to know if there is walkaround for this.
This is the code I use:
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&v=3.exp&signed_in=true"></script>
<script>
var posiciones;
var rendererOptions = {
draggable: true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var map;
var polys = new Array();
var resultado;
var routCoordinates;
var respuesta;
var myPolygons = [
<asp:Repeater ID='rptMarkers' runat='server'>
<ItemTemplate>
{
"name": '<%# Eval("carajo") %>',
"coordinates": [
'<%# Eval("poligono1") %>',
'<%# Eval("poligono2") %>',
'<%# Eval("poligono3") %>',
'<%# Eval("poligono4") %>'
]
}
</ItemTemplate>
<SeparatorTemplate>
,
</SeparatorTemplate>
</asp:Repeater>
];
function drawPolygon(poly, polyLabel) {
var options = {
paths: poly,
strokeColor: '#AA2143',
strokeOpacity: 1,
strokeWeight: 2,
fillColor: "#FF6600",
fillOpacity: 0.7,
polyTitle: polyLabel
};
newPoly = new google.maps.Polygon(options);
newPoly.setMap(map);
polys.push(newPoly);
}
function sendPolygonForDrawing() {
for (var i = 0; i < myPolygons.length; i++) {
poly = new Array();
var coord = myPolygons[i].coordinates;
var lng = coord.length;
for (var j = 0; j < lng; j++) {
var longit_Latid = coord[j].split(',');
poly.push(new google.maps.LatLng(parseFloat(longit_Latid[0]), parseFloat(longit_Latid[1])));
}
drawPolygon(poly, myPolygons[i].name);
poly.pop();
}
}
var trucka = new google.maps.LatLng(21.984797, -102.27668);
function initialize() {
var mapOptions = {
zoom: 12,
center: trucka
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
//directionsDisplay.setPanel(document.getElementById('directionsPanel'));
directionsDisplay.setPanel(document.getElementById('hola'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {
computeTotalDistance(directionsDisplay.getDirections());
});
calcRoute();
}
function fncRouteZoneIntersection(response) {
//var myRoute = response.routes[0].legs[1];
var myRoute = response.routes[0].overview_path;
var lngLatCordinates = new Array();
// for (var i = 0; i < myRoute.steps.length; i++) {
for (var i = 0; i < myRoute.length; i++) {
var marker = new google.maps.Marker({
map: map,
// position: myRoute.steps[i].start_point
position: myRoute[i]
});
// lngLatCordinates.push(myRoute.steps[i].start_point);
lngLatCordinates.push(myRoute[i]);
}
return lngLatCordinates;
}
function calcRoute() {
sendPolygonForDrawing();
var lat = document.getElementById('hdnLatitudOrigen').value;
var lon = document.getElementById('hdnLongitudOrigen').value;
var request = {
origin: new google.maps.LatLng(lat, lon),
destination: new google.maps.LatLng(document.getElementById('hdnLatitudDestino').value, document.getElementById('hdnLongitudDestino').value),
waypoints: [
{ location: new google.maps.LatLng(document.getElementById('hdnLatitudParada1').value, document.getElementById('hdnLongitudParada1').value) }
/*{ location: new google.maps.LatLng(document.getElementById('hdnLatitudParada2').value, document.getElementById('hdnLongitudParada2').value) },
{ location: new google.maps.LatLng(document.getElementById('hdnLatitudParada3').value, document.getElementById('hdnLongitudParada3').value) },
{ location: new google.maps.LatLng(document.getElementById('hdnLatitudParada4').value, document.getElementById('hdnLongitudParada4').value) },
{ location: new google.maps.LatLng(document.getElementById('hdnLatitudParada5').value, document.getElementById('hdnLongitudParada5').value) }*/
],
travelMode: google.maps.TravelMode.DRIVING,
provideRouteAlternatives: true,
avoidHighways: false,
avoidTolls: false
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
respuesta = response;
var routCoordinates = fncRouteZoneIntersection(response);//this function populates the routCoordinates with the JSON data of the route.
var exist = new Array();
for (var i = 0; i < polys.length; i++) {//polys holds all polygons objects.
for (var j = 0; j < routCoordinates.length; j++){
// if (google.maps.geometry.poly.containsLocation(new google.maps.LatLng(routCoordinates[j].k, routCoordinates[j].A), polys[i]) == true){
if (google.maps.geometry.poly.containsLocation(routCoordinates[j], polys[i]) == true) {
//alert('CARAJO!');
alert(polys[i].polyTitle);
exist.push(polys[i].polyTitle);
break;
/*this breaks the loop checking when a point is found inside a polygon
and go check the next one, because knowing that one point of the route is
inside a polygon is enough*/
}
}
}
google.maps.event.addListener(directionsDisplay, 'directions_changed', updateInfo);
updateInfo();
}
});
}
function calcularPaso(){
var tolo = fncRouteZoneIntersection(respuesta);
var existe = new Array();
for (var i = 0; i < polys.length; i++) {
for (var j = 0; j < tolo.length; j++) {
if (google.maps.geometry.poly.containsLocation(tolo[j], polys[i]) == true) {
//alert('simon');
}
}
}
}
function updateInfo() {
//alert('carajo')
posiciones = '';
var route = directionsDisplay.getDirections().routes[0];
// var routes = response.routes;
var points = route.overview_path;
var ul = document.getElementById("vertex");
var elems = ul.getElementsByTagName("li")
for (var i = 0; i < elems.length; i++) {
elems[i].parentNode.removeChild(elems[i]);
}
for (var i = 0; i < points.length; i++) {
var li = document.createElement('li');
li.innerHTML = getLiText(points[i]);
ul.appendChild(li);
posiciones = posiciones + getLiText(points[i]);
}
document.getElementById("txtResultado").value = posiciones;
//document.getElementById("hdnResultado").value = posiciones;
calcularPaso();
}
function getLiText(point) {
var lat = point.lat(),
lng = point.lng();
return "2 " + lng + "," + lat;
return lat + ",2 " + lng + ",";
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.0;
document.getElementById('total').innerHTML = total + ' km';
}
google.maps.event.addDomListener(window, 'load', initialize);
<div id="map-canvas" style="width: 100%; height: 400px"></div>
<div id="hola">
<label>Puntos</label>
<ul id="vertex" runat="server"></ul>
</div>
<div id="directionsPanel" style="width: 30%; height: 600px;">
<p>
Total Distance: <span id="total"></span>
</p>
</div>
On the image I am sending, you can see the polygon colored in yellow.
Hope you can help.
Thanks!
You can use [containsLocation(point:LatLng, polygon:Polygon)][1] method in the geometry library. You can use this to find whether a given point falls within a polygon, pass the point and the polygon to google.maps.geometry.poly.containsLocation(). The functions returns true if the point is within the polygon or on its edge.
https://developers.google.com/maps/documentation/javascript/geometry#containsLocation

Categories

Resources