Creating Polyine From Latitude Longitude in google maps? - google-maps

I am trying to create a polyline from google maps v3 api. I know how add polyline on click but i want to create polyline from latitude & longitude value which will be in loop. How can i do that ?
var network_url = decodeURIComponent(document.URL);
//var network_url = " http://testNetwork.com?param[]=(12.983147333223707, 77.49687217431642)&param[]=(12.95035965289418, 77.54871391015627)";
var location_array = split_url(network_url);
for(var i = 0; i<location_array.length; i++)
{
//(12.960062579720846,%2077.48313926416017)
var loc = location_array[i] ; //==>(12.77, 24.87)
var split_arr1 = loc.split("(");
var result_split_arr1 = split_arr1[1].split( ")" );
var split_latLon = result_split_arr1[0];
var result_split = split_latLon.split(",");
var split_lat = result_split[0];
var split_lon = result_split[1];
marker = new google.maps.Marker({
position: new google.maps.LatLng(split_lat, split_lon),
map: map
});
///////////POLYLINE DRAWing /////////////////////////////
/////////////END OF POLYLINE ////////////////////
}
}
thank you.

Check out the documentation for the polyline. It takes an array of LatLng's.
Loop through your and points, throw them in an array, and pass them to the PolyLine through the constructor or .setPath().
https://developers.google.com/maps/documentation/javascript/reference#Polyline
Edit: Example. (I didn't run it).
var location_array = split_url(network_url);
var path = [];
for(var i = 0; i<location_array.length; i++)
{
//(12.960062579720846,%2077.48313926416017)
var loc = location_array[i] ; //==>(12.77, 24.87)
var split_arr1 = loc.split("(");
var result_split_arr1 = split_arr1[1].split( ")" );
var split_latLon = result_split_arr1[0];
var result_split = split_latLon.split(",");
var split_lat = result_split[0];
var split_lon = result_split[1];
var latLng = new google.maps.LatLng(split_lat, split_lon);
path.push(latLng)
marker = new google.maps.Marker({
position: latLng,
map: map
});
}
var flightPath = new google.maps.Polyline({
path: path,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
}

Related

Getting an error on with my code on apps script

[UserCodeAppPanel Error(https://i.stack.imgur.com/CNyuI.png)
I am using SpreadsheetApp to show location within a radius from the spreadsheet and I am getting this error. Could someone assist me with what is wrong in my code in order to fix this error?
Below is my code in the Index.html file using google sheets app script:
<!DOCTYPE html>
<html>
<head>
<title>Draw Circles using Google Map API</title>
<script src="https://maps.google.com/maps/api/js?key=AIzaSyArRKMKMbDrCz1h1KKpKbfqOfzNGfZiT_o"></script>
<!--PLEASE NOTE: As of June 22 2016, Google Maps require an API key.
* GET YOUR API KEY FROM ... https://developers.google.com/maps/documentation/javascript/get-api-key
* ONCE YOU GET THE KEY, REPLACE 'js?sensor=false' IN THE ABOVE URL WITH "js?key=YOUR_NEW_API_KEY".-->
</head>
<body>
<div id="mapContainer" style="width:750px;height:350px;"></div>
</body>
</html>
<script>
// LOCATION IN LATITUDE AND LONGITUDE.
function onFormSubmit(event) {
var ss = SpreadsheetApp.getActiveSheet();
// MAP ATTRIBUTES
var center = new google.maps.LatLng(33.6608243, -84.4954219);
var mapAttr = {
center: center,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// THE MAP TO DISPLAY.
var map = new google.maps.Map(document.getElementById("mapContainer"), mapAttr);
var circle = new google.maps.Circle({
center: center,
map: map,
radius: 16093.40, // IN METERS.
fillColor: '#FF6600',
fillOpacity: 0.3,
strokeWeight: 0, // DON'T SHOW CIRCLE BORDER.
content:'<h1>Atlanta Community Food FoodBank</h1>'
});
var marker = new google.maps.Marker({
position:{lat:33.6608243, lng:-84.4954219},
map:map,
icon: 'https://img.icons8.com/fluent/48/000000/marker.png',
draggable: false
});
var information = new google.maps.InfoWindow({
content: '<h4>Atlanta Community Food Bank</h4>'
});
marker.addListener('click', function() {
information.open(map, marker);
})
var lastRow = ss.getLastRow();
var markers = "coords:[{lat:"+ss.getRange('D2').getValue()+", "+"lng:"+ss.getRange('E2').getValue()+"}]";
for(var i = 1; i < markers.length; i++){
addMarker(markers[i]);
}
function addMarker(props){
var marker = new google.maps.Marker({
position:props.coords,
map:map,
})
}
}
google.maps.event.addDomListener(window, 'load', onFormSubmit);
</script>
</html>
I want to show location inside and outside of radius from the latitude and longitude on spreadsheet
enter image description here
Code.gs
Code.gs File
UserCodeAppPanel Error
I would suggest you replace the following line of code first. Or simply delete.
var ss = SpreadsheetApp.getActiveSheet();
With
// var ss = SpreadsheetApp.getActiveSheet();
Second replace the follow code.
var lastRow = ss.getLastRow();
var markers = "coords:[{lat:"+ss.getRange('D2').getValue()+", "+"lng:"+ss.getRange('E2').getValue()+"}]";
for(var i = 1; i < markers.length; i++){
addMarker(markers[i]);
}
function addMarker(props){
var marker = new google.maps.Marker({
position:props.coords,map:map,
})
}
With
function addMarker(props){
var marker = new google.maps.Marker({
position:props.coords,
map:map,
})
}
google.script.run.withSuccessHandler(
function(markers) {
for(var i = 1; i < markers.length; i++) {
addMarker(markers[i]);
}
}
).getMarkers();
And include the following in the server code Code.gs.
function getMarkers() {
try {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Name");
var markers = [{lat:ss.getRange('D2').getValue(),lng:ss.getRange('E2').getValue()}];
return markers;
}
catch(err) {
console.log("Error in getMarkers: "+err);
}
}

Uncaught RangeError: Maximum call stack size exceeded log

While plotting multiple markers on a Google map, I got an Uncaught RangeError: Maximum call stack size exceeded error message in the log for Ionic framework.
I am using a Cordova Google plugin for the map. Can anyone figure out where the error is in my code?
var autocompleteFrom = new google.maps.places.Autocomplete(inputFrom, options);
var autocompleteto = new google.maps.places.Autocomplete(inputto,options);
google.maps.event.addListener(autocompleteFrom, 'place_changed', function() {
var bounds = new google.maps.LatLngBounds();
var place = autocompleteFrom.getPlace();
$rootScope.fromLat = place.geometry.location.lat();
$rootScope.fromLng = place.geometry.location.lng();
$rootScope.from = place.formatted_address;
$scope.placesfrom = $rootScope.from;
fromlat = $rootScope.fromLat;
fromlng = $rootScope.fromLng;
var Mapoptions ={
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl:false,
zoomControl:false,
draggable:true,
mapTypeControl:false,
scaleControl:false,
streetViewControl:false,
overviewMapControl:false,
rotateControl:true
}
var googlemaphome = document.getElementById('googlemap-home');
var Map = new google.maps.Map(googlemaphome,Mapoptions);
var marker;
var markers = [
[fromlat,fromlng],
[28.6328,77.2197]
];
for(var i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
icon: 'img/marker.png',
map: Map
});
}
Map.fitBounds(bounds);
var boundsListener = google.maps.event.addListener((Map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
$scope.$apply();
});
`
I think the issue is here:
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
Since the subarrays in your markers[] array only have 2 elements, and the index for arrays starts at 0, I believe you should change this line to
var position = new google.maps.LatLng(markers[i][0], markers[i][1]); //use 0 and 1 instead of 1 and 2

trouble with fusion table map, custom marker and infowindow

I have been working on a fusion table map. I am trying to add custom markers and infowindows but I am having issues getting it to show my markers and infowindows. I think I have something out of order or maybe a few syntax errors I am unable to find. I have sort of confused myself up a bit on the process. I would appreciate any help.
var tableId ="1zFwXiOkWbKCY9xRGvXBdHjUkTsirnwbr77WjTds"; // original table
google.load('visualization', '1');
var map;
var markers = [];
var infoWindow = new google.maps.InfoWindow();
function initialize() {
var ak = new google.maps.LatLng(64.958056,-147.618333);
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: ak,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var queryStr = "SELECT name, lat, lng, description FROM "+tableId+" ORDER BY name";
document.getElementById('info').innerHTML += queryStr +"<br>";
var queryText = encodeURIComponent(queryStr);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
query.send(getData);
}
function getData(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var dt = response.getDataTable();
document.getElementById('info').innerHTML += "rows="+dt.getNumberOfRows()+"<br>";
for (var i = 0; i < dt.getNumberOfRows(); i++) {
var lat = dt.getValue(i,1);
var lng = dt.getValue(i,2);
var name = dt.getValue(i,0);
var description = dt.getValue(i,3);
}
var pt = new google.maps.LatLng(lat, lng);
var html = "<span style='font-size:13px;font-weight:bold;color:#236192;'>" + name + "</span><p style='font-size:12px;'>" + description + "</p>";
var info = html;
}
function createMarker(pt,info) {
var iconURL = 'uaf-icon.png';
var iconSize = new google.maps.Size(29,60);
var iconOrigin = new google.maps.Point(0,0);
var iconAnchor = new google.maps.Point(15,60);
var myIcon = new google.maps.MarkerImage(iconURL, iconSize, iconOrigin, iconAnchor);
var shadowURL = 'uaf-shadow.png';
var shadowSize = new google.maps.Size(63, 60);
var shadowOrigin = new google.maps.Point(0, 0);
var shadowAnchor = new google.maps.Point(15, 60);
var myShadow = new google.maps.MarkerImage(shadowURL, shadowSize, shadowOrigin, shadowAnchor);
var iconShape = [18,0,20,1,22,2,23,3,24,4,25,5,26,6,27,7,27,8,28,9,28,10,28,11,28,12,28,13,28,14,28,15,28,16,28,17,28,18,28,19,27,20,27,21,26,22,26,23,25,24,24,25,23,26,21,27,20,28,16,29,21,31,21,32,21,33,21,34,21,35,20,36,20,37,20,38,19,39,19,40,19,41,18,42,18,43,18,44,18,45,17,46,17,47,17,48,17,49,16,50,16,51,16,52,15,53,15,54,15,55,14,56,14,57,14,58,14,59,13,59,13,58,13,57,13,56,12,55,12,54,12,53,12,52,11,51,11,50,11,49,11,48,11,47,10,46,10,45,10,44,10,43,9,42,9,41,9,40,9,39,9,38,8,37,8,36,8,35,8,34,8,33,7,32,7,31,12,29,9,28,7,27,6,26,4,25,3,24,3,23,2,22,1,21,1,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,1,9,1,8,2,7,2,6,3,5,4,4,5,3,6,2,8,1,10,0,18,0];
var myMarkerShape = {
coord: iconShape,
type: 'poly'
};
var myMarkerOpts = {
position: point,
map: map,
icon: myIcon,
shadow: myShadow,
shape: myMarkerShape
};
var marker = new google.maps.Marker(myMarkerOpts);
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infoWindow.close();
infoWindow.setContent(info);
infoWindow.open(map,marker);
});
}
function myclick(num) {
google.maps.event.trigger(markers[num], "click");
}
first get the map displaying with default markers. You aren't calling the createMarker function (or creating any markers):
for (var i = 0; i < dt.getNumberOfRows(); i++) {
var lat = dt.getValue(i,1);
var lng = dt.getValue(i,2);
var name = dt.getValue(i,0);
var description = dt.getValue(i,3);
var pt = new google.maps.LatLng(lat, lng);
createMarker(pt,"<b>"+name+"</b><br>"+description);
}
there is a typo in createMarker (there is no "point" variable in the scope of the function, it should be "pt"), look for and address any errors in the javascript console.
function createMarker(pt,info) {
var iconURL = 'uaf-icon.png';
var iconSize = new google.maps.Size(29,60);
var iconOrigin = new google.maps.Point(0,0);
var iconAnchor = new google.maps.Point(15,60);
var myIcon = new google.maps.MarkerImage(iconURL, iconSize, iconOrigin, iconAnchor);
var shadowURL = 'uaf-shadow.png';
var shadowSize = new google.maps.Size(63, 60);
var shadowOrigin = new google.maps.Point(0, 0);
var shadowAnchor = new google.maps.Point(15, 60);
var myShadow = new google.maps.MarkerImage(shadowURL, shadowSize, shadowOrigin, shadowAnchor);
var iconShape = [18,0,20,1,22,2,23,3,24,4,25,5,26,6,27,7,27,8,28,9,28,10,28,11,28,12,28,13,28,14,28,15,28,16,28,17,28,18,28,19,27,20,27,21,26,22,26,23,25,24,24,25,23,26,21,27,20,28,16,29,21,31,21,32,21,33,21,34,21,35,20,36,20,37,20,38,19,39,19,40,19,41,18,42,18,43,18,44,18,45,17,46,17,47,17,48,17,49,16,50,16,51,16,52,15,53,15,54,15,55,14,56,14,57,14,58,14,59,13,59,13,58,13,57,13,56,12,55,12,54,12,53,12,52,11,51,11,50,11,49,11,48,11,47,10,46,10,45,10,44,10,43,9,42,9,41,9,40,9,39,9,38,8,37,8,36,8,35,8,34,8,33,7,32,7,31,12,29,9,28,7,27,6,26,4,25,3,24,3,23,2,22,1,21,1,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,1,9,1,8,2,7,2,6,3,5,4,4,5,3,6,2,8,1,10,0,18,0];
var myMarkerShape = {
coord: iconShape,
type: 'poly'
};
var myMarkerOpts = {
position: pt,
map: map,
icon: myIcon,
shadow: myShadow,
shape: myMarkerShape */
};
var marker = new google.maps.Marker(myMarkerOpts);
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infoWindow.close();
infoWindow.setContent(info);
infoWindow.open(map,marker);
});
}
working example (with default icons)

Finding the great circle distance between three points using the Google Maps API v3

Unfortunately I was not able to find any code / example how to draw great circle distance *between three(3) points on google maps*??
Here is the javascript for two points. How can I make it work with three points?
var geocoder;
var map;
var addresses;
var results;
var dist;
function initialize() {
geocoder = new google.maps.Geocoder();
address1 = document.getElementById("distancefrom").value;
address2 = document.getElementById("distanceto").value;
(distance(address1, address2));
}
function distance(add1, add2) {
if (!geocoder)
return 'Error, no geocoder';
addresses = new Array(2);
addresses[0] = add1;
addresses[1] = add2;
results = new Array(2);
results[0] = new Array(2);
results[1] = new Array(2);
results[0][0] = 0; results[0][1] = 0; results[1][0] = 0; results[1][1] = 0.87;
geocoded(1);
}
function geocoded(i) {
geocoder.geocode( { 'address': addresses[i] }, function(res, status) {
if (status == google.maps.GeocoderStatus.OK) {
results[i][0] = parseFloat(res[0].geometry.location.lat());
results[i][1] = parseFloat(res[0].geometry.location.lng());
i--;
if (i >= 0)
geocoded(i);
else {
var latlng1 = new google.maps.LatLng(results[0][0], results[0][1]);
var latlng2 = new google.maps.LatLng(results[1][0], results[1][1]);
dist = google.maps.geometry.spherical.computeDistanceBetween(latlng1, latlng2)/1000;
var dmi = 0.539957*dist;
document.getElementById('totaldistancemiles').value = dmi.toFixed(2);
document.getElementById('totaldistancekm').value = dist.toFixed(2);
showMap(latlng1,latlng2);
}
}
});
}
function showMap(location1,location2) {
latlng = new google.maps.LatLng((location1.lat()+location2.lat())/2,
(location1.lng()+location2.lng())/2);
faddress1 = document.getElementById("distancefrom").value;
faddress2 = document.getElementById("distanceto").value;
var mapOptions =
{
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
var flightPlanCoordinates = [
location1,
location2
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: .5,
geodesic: true,
strokeWeight: 3
});
flightPath.setMap(map);
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#000000",
strokeOpacity: .5,
strokeWeight: 0
});
flightPath.setMap(map);
var igreen= 'https://dl.dropboxusercontent.com/u/85343999/igreen.gif';
var marker = new google.maps.Marker({
map: map,
icon: igreen,
position: location1
});
var latlngbounds;
latlngbounds = new google.maps.LatLngBounds();
latlngbounds.extend( location1);
latlngbounds.extend( location2);
map.fitBounds(latlngbounds);
var infowindow = new google.maps.InfoWindow();
infowindow.setContent(faddress1);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
var marker2 = new google.maps.Marker({
map: map,
icon: igreen,
position: location2
});
var infowindow2 = new google.maps.InfoWindow();
infowindow2.setContent(faddress2);
google.maps.event.addListener(marker2, 'click', function() {
infowindow2.open(map, marker2);
});
}
The following code uses Googles geometry library to calculate distances between points.The locations are stored in this case in an array, but can be obtained from textboxes etc. The distances are given in metres .
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script type="text/javascript">
var coords = [
[35.733972, -5.881999],
[35.734077, -5.881033],
[35.736898, -5.877771],
];
function calcDistance() {
var first = new google.maps.LatLng(coords[0][0],coords[0][1]);
var second = new google.maps.LatLng(coords[1][0],coords[1][1]);
var third = new google.maps.LatLng(coords[2][0],coords[2][1]);
var distance1 = google.maps.geometry.spherical.computeDistanceBetween(first, second);
var distance2 = google.maps.geometry.spherical.computeDistanceBetween(first, third);
var distance3 = google.maps.geometry.spherical.computeDistanceBetween(second, third);
showDistance(distance1,distance2,distance3);
}
function showDistance(distance1,distance2,distance3) {
document.write("Distance1 "+distance1 + " metres <br>");
document.write("Distance2 "+distance2 + " metres <br>");
document.write("Distance3 "+distance3 + " metres <br>");
}

Plot multiple points on google map using API

I am trying to show different points on any route on google map using the API. I want to pass in starting, stopping and finishing locations. Is this possible using the javascript API or would I need to look into other options such as geolocation?
I am using the following code to achieve this:
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.(-64.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=52554&sensor=false&callback=initialize";
document.body.appendChild(script);
}
Here is my code.
`<script type="text/javascript">
var geocoder = null;
var arr = new Array();
var arr1 = new Array();
var arr2 = new Array();
var map = null;
var chr;
var baseIcon = null;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng('<%=Request["Lat"]%>', '<%=Request["Long"]%>'), 13);
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
baseIcon = new GIcon();
// baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(25, 30);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
baseIcon.infoShadowAnchor = new GPoint(18, 25);
// Creates a marker whose info window displays the letter corresponding to the given index.
function createMarker(point, index) {
// Create a lettered icon for this point using our icon class
var letter = String.fromCharCode("A".charCodeAt(0) + index);
var letteredIcon = new GIcon(baseIcon);
letteredIcon.image = "markers/marker" + index + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon: letteredIcon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function () {
marker.openInfoWindowHtml("<table><tr><td><img src=markers/marker" + index + ".png length=25 width=25 /></td>" + "<td>" + arr2[index] + "</td></tr></table>");
});
return marker;
}
for (var i = 0; i < arr.length; i++) {
var latlng = new GLatLng(arr[i], arr1[i]);
map.addOverlay(createMarker(latlng, i));
}
}
}
`