I have two arrays containing latitude and longtitude of 7 locations,and I use the following
code for getting the location of these 7 points:
var geocoder;
initialize();
codeLatLng();
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng() {
var arrlat=[45.95268273, 47.00196833,45.99168238, 46.2186456, 45.91612197, 45.91606814, 45.91606814];
var arrlon=[-66.68426012, -65.56480221, -63.98068545, -64.44419501, -66.74801471, -66.74810832, -66.74810832];
var input = document.getElementById("latlng").getAttribute('value');
console.log(input);
var latlngStr = input.split(",", 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
for(var i=0;i<arrlat.length;i++)
{
var latlng = new google.maps.LatLng(arrlat[i], arrlon[i]);
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
//document.getElementById("test").innerHTML = '' + (results[4].formatted_address); + ''
alert(results[4].formatted_address);
});
}
}
whenever I feed the arrays with 5 of less elements the code works properly but for more than 5 I get 5 alert showing the location of the first 5 elements but for the last 2 I get the following error:
Uncaught TypeError: Cannot read property '4' of null
And here is the Jfiddle link:
link
Can anyone help?
Code more defensively. Check the status of the response before using it. If it isn't "OK", there won't be any results to process.
function codeLatLng() {
var arrlat=[45.95268273, 47.00196833,45.99168238, 46.2186456, 45.91612197, 45.91606814, 45.91606814];
var arrlon=[-66.68426012, -65.56480221, -63.98068545, -64.44419501, -66.74801471, -66.74810832, -66.74810832];
var input = document.getElementById("latlng").getAttribute('value');
console.log(input);
var latlngStr = input.split(",", 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
for(var i=0;i<arrlat.length;i++)
{
var latlng = new google.maps.LatLng(arrlat[i], arrlon[i]);
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK ) {
//document.getElementById("test").innerHTML = '' + (results[4].formatted_address); + ''
if (results.length >= 5)
alert(results[4].formatted_address);
else alert("less than 5 results");
} else alert("reverse geocode failed, status="+status);
});
}
}
See the documentation on Status Codes for what the failure codes mean.
Related
I am working with ASTER images and I am trying to convert radiance values to reflectance. Currently, I converted DN values to radiance and I don't know what else to do. Also, I found a Landsat function, but I don't know if it works for this case. This is my code:
var AOI = ee.Geometry.Polygon([
[-75.01530862531565,9.762481145514606],[-74.58134866437815,9.762481145514606],
[-74.58134866437815,10.27637106477599],[-75.01530862531565,10.27637106477599]]);
var dataset = ee.ImageCollection('ASTER/AST_L1T_003')
.filter(ee.Filter.date('2000-01-01', '2020-10-30'))
.filterBounds(AOI)
.filterMetadata('CLOUDCOVER', 'less_than', 1)
.filter(ee.Filter.and(
ee.Filter.notNull(['GAIN_COEFFICIENT_B01']),
ee.Filter.notNull(['GAIN_COEFFICIENT_B02']),
ee.Filter.notNull(['GAIN_COEFFICIENT_B3N']),
ee.Filter.notNull(['GAIN_COEFFICIENT_B04']),
ee.Filter.notNull(['GAIN_COEFFICIENT_B05']),
ee.Filter.notNull(['GAIN_COEFFICIENT_B06']),
ee.Filter.notNull(['GAIN_COEFFICIENT_B07']),
ee.Filter.notNull(['GAIN_COEFFICIENT_B08']),
ee.Filter.notNull(['GAIN_COEFFICIENT_B09'])));
print(dataset)
// red and NIR channel digital numbers to at sensor radiance
function bands (img) {
var gainB1 = 0.676;
var gainB2= 0.708;
var gainB3N = 0.862;
var gainB4= 0.2174;
var gainB5 = 0.0696;
var gainB6= 0.0625;
var gainB7 = 0.0597;
var gainB8= 0.0417;
var gainB9 = 0.0318;
var rad_b1 = (img.select('B01').subtract(1)).multiply(gainB1);
var rad_b2 = (img.select('B02').subtract(1)).multiply(gainB2);
var rad_b3 = (img.select('B3N') .subtract(1)).multiply(gainB3N);
var rad_b4 = (img.select('B04').subtract(1)).multiply(gainB4);
var rad_b5 = (img.select('B05') .subtract(1)).multiply(gainB5);
var rad_b6 = (img.select('B06').subtract(1)).multiply(gainB6);
var rad_b7 = (img.select('B07').subtract(1)).multiply(gainB7);
var rad_b8 = (img.select('B08').subtract(1)).multiply(gainB8);
var rad_b9 = (img.select('B09').subtract(1)).multiply(gainB9);
return (rad_b1).addBands(rad_b2).addBands(rad_b3).addBands(rad_b4)
.addBands(rad_b5).addBands(rad_b6).addBands(rad_b7)
.addBands(rad_b8).addBands(rad_b9);
}
// add all selected bands with radiance values
var rad_bands =dataset.map(bands)
print(rad_bands)
function copyProps(index){
var source = ee.Image(dataset.toList(dataset.size()).get(index))
var dest = ee.Image(rad_bands.toList(rad_bands.size()).get(index))
var image = ee.Image(dest.copyProperties(source))
return image
}
var seq = ee.List.sequence(0, rad_bands.size().subtract(1))
print(seq)
var final_col = ee.ImageCollection(seq.map(copyProps))
https://code.earthengine.google.com/5b2dfc9b609ba5738be49ae2915d3980
I have Yandex map tiles (Russian) working in Google Maps API v2 but something's not working in Google Maps API v3, see the following jsfiddle: http://jsfiddle.net/VkGjq/1/
Note that when switching between the Google road map and the Yandex tiles they don't line up & the marker is in the wrong position.
For Maps v2, I made an equivalent jsfiddle but it's broken since it needs an API key: http://jsfiddle.net/ggrgQ/1/
You can see similar code here, but you will have to navigate to Moscow manually as Yandex doesn't have any decent data outside of Russia: http://gpsloglabs.com/share/2367c16f3a0e75b05ac8a5529afba225dd929518/
I don't recall where I got the v3 code, but the constants appear to roughly correspond to the v2 version. Other than that, I don't understand what the projection is doing so I'm stuck.
Any ideas?
The code from the jsfiddle is as follows:
var center = new google.maps.LatLng(55.75, 37.62);
var mapOptions = {
zoom: 10,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
new google.maps.Marker({map: map, position: center});
map.mapTypes.set("Yandex",
new google.maps.ImageMapType(
{getTileUrl: function(coord, zoom) {
return "http://vec0"+((coord.x+coord.y)%5)+".maps.yandex.net/tiles?l=map&v=2.16.0&x=" +
coord.x + "&y=" + coord.y + "&z=" + zoom + "";
},
tileSize: new google.maps.Size(256, 256),
isPng: true,
alt: "Yandex",
name: "Yandex",
projection: new YandexProjection(),
maxZoom: 17}));
map.setOptions({mapTypeControlOptions: {mapTypeIds: [google.maps.MapTypeId.ROADMAP, "Yandex"]} });
function YandexProjection() {
this.pixelOrigin_ = new google.maps.Point(128,128);
var MERCATOR_RANGE = 256;
this.pixelsPerLonDegree_ = MERCATOR_RANGE / 360;
this.pixelsPerLonRadian_ = MERCATOR_RANGE / (2 * Math.PI);
this.fromLatLngToPoint = function(latLng) {
function atanh(x) {
return 0.5*Math.log((1+x)/(1-x));
}
function degreesToRadians(deg) {
return deg * (Math.PI / 180);
}
function bound(value, opt_min, opt_max) {
if (opt_min != null) value = Math.max(value, opt_min);
if (opt_max != null) value = Math.min(value, opt_max);
return value;
}
var origin = this.pixelOrigin_;
var exct = 0.0818197;
var z = Math.sin(latLng.lat()/180*Math.PI);
return new google.maps.Point(origin.x + latLng.lng() *this.pixelsPerLonDegree_,
Math.abs(origin.y - this.pixelsPerLonRadian_*(atanh(z)-exct*atanh(exct*z))));
};
this.fromPointToLatLng = function(point) {
var origin = this.pixelOrigin_;
var lng = (point.x - origin.x) / this.pixelsPerLonDegree_;
var latRadians = (point.y - origin.y) / -this.pixelsPerLonRadian_;
var lat = Math.abs((2*Math.atan(Math.exp(latRadians))-Math.PI/2)*180/Math.PI);
var Zu = lat/(180/Math.PI);
var Zum1 = Zu+1;
var exct = 0.0818197;
var yy = -Math.abs(((point.y)-128));
while (Math.abs(Zum1-Zu)>0.0000001){
Zum1 = Zu;
Zu = Math.asin(1-((1+Math.sin(Zum1))*Math.pow(1-exct*Math.sin(Zum1),exct))
/ (Math.exp((2*yy)/-(256/(2*Math.PI)))*Math.pow(1+exct*Math.sin(Zum1),exct)));
}
if (point.y>256/2) {
lat=-Zu*180/Math.PI;
} else {
lat=Zu*180/Math.PI;
}
return new google.maps.LatLng(lat, lng);
};
return this;
}
It turns out that the projection property can't be set via the ImageMapTypeOptions and has to be assigned after the ImageMapType has been constructed, this jsfiddle now works: http://jsfiddle.net/VkGjq/2/
var yandexMapType = new google.maps.ImageMapType(
{getTileUrl: function(coord, zoom) {
return "http://vec0"+((coord.x+coord.y)%5)+".maps.yandex.net/tiles?l=map&v=2.16.0&x=" +
coord.x + "&y=" + coord.y + "&z=" + zoom + "";
},
tileSize: new google.maps.Size(256, 256),
isPng: true,
alt: "Yandex",
name: "Yandex",
maxZoom: 17});
// projection is ignored if passed to MapTypeOptions
yandexMapType.projection = new YandexProjection();
map.mapTypes.set("Yandex", yandexMapType);
By license agreement you can't use yandex maps without yandex api. You can't use yandex tiles in leaflet.
You need to wrap yandex api or use http://leafletjs.com/plugins.html
Or write own a wrapper.
Example https://all-maps.herokuapp.com/
https://github.com/artamonovdev/all-maps
I'm completely lost.
I have my html form, where I can write a city.
When the form is send, a data array is send in a each loop, below is the code :
geocoder = new google.maps.Geocoder();
$.each(data['list'],function(i,el)
{
var address = el.address1+','+el.city+' '+el.zipcode;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var getZipCode = $("#zipcode").val();
var getCity = $("#city").val();
geocoder.geocode( { 'address': getCity+' '+getZipCode }, function(resultsTwo, statusTwo) {
if (status == google.maps.GeocoderStatus.OK) {
var distanceKm = google.maps.geometry.spherical.computeDistanceBetween(results[0].geometry.location, resultsTwo[0].geometry.location);
var distanceMiles = distanceKm/1000*0.621371;
str = str +'<article><div class="leftDesc"><header><h3><span class="letter">'+alphabet[i]+'.</span>'+el.store_name+'</h3></header>';
str = str +'<div class="addressEnonce">Address:</div><div class="addressBig"><p class="address">'+el.address1+'</p>';
/*str = str +'<p>'+el.address2+'</p>';*/
str = str +'<br /><p class="city">'+el.city+'</p>';
str = str +' <p class="zipcode">'+el.zipcode+'</p>';
str = str +' <p class="state">'+el.state+'</p></div></div>';
str = str +'<div class="rightDesc"><p class="distance">Distance: '+distanceMiles+' Miles</p>';
str = str +'<p>'+el.description+'</p></div>';
str = str + '<p>Show on Map</p>';
if((i+1) < data['list'].length){
switch(i % 4){
case 0:
str = str +'<img src="img/line.png" >';
break;
case 1:
str = str +'<img src="img/line.png" >';
break;
case 2:
str = str +'<img src="img/line.png" >';
break;
}
}
str = str +'</article>';
tweets.append(str);
}
});
}
});
}) })
So the code is good, for Washington by example, I will have 3 items showed, also I want have 2! The first item is in double one =7
I think the problem is I must to put a callback function, because this is the asynchronous method in geocodes loops which cause the trouble... But how please ?!
The fact that it is asynchronous is the problem. You need to use a closure. Here's an example:
$.each(data['list'],function(i,el) {
var address = el.address1+','+el.city+' '+el.zipcode;
geocoder.geocode( { 'address': address}, (function(address1, city, zipcode) {
return function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
geocoder.geocode( { 'address': city+' '+zipcode },
function(resultsTwo, statusTwo) {
// ...
});
}
};
})(el.address1, el.city, el.zipcode));
});
The code below is used to make google-fusion-table work with markercluster together.
(referrence: http://www.cs.gsu.edu/~ashrestha2/vis/prjmap2.html
Give honor to the author very much)
However, when I was trying to follow the example in the above link, I succeed in test 1 but failed in test 2. The test 1 used a fusion table with two columns and the test 2 used a fusion table with three columns. I don't know why I failed as I only added one more column for test 2.
google.load('visualization', '1.0', {"callback":initialize});
//var tableid = '1_6G1c1l7glLHRuOU7uvH8oONbObDf_cOtZS21Rc', atlcenter = new google.maps.LatLng(33.755711,-84.388372); //test1_success
var tableid = '1IagEEylcnbuPygCES70ipnvb9q0C5OgmGPNyx9o1', atlcenter = new google.maps.LatLng(33.755711,-84.388372); //test2_fail
var mapMain, markers, dataTable = null, mc = null;
function initialize() {
mapMain = new google.maps.Map(document.getElementById('map-canvas'), {
center: atlcenter,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
mc = new MarkerClusterer(mapMain);
queryMap("select * from "+tableid);
}
function queryMap(queryText){
mc.clearMarkers(); markers=[];
var tmp = 'http://www.google.com/fusiontables/gvizdata?tq='+encodeURIComponent(queryText);
var query = new google.visualization.Query(tmp);
query.send(handleQueryResponse);
}
function handleQueryResponse(response){
dataTable = response.getDataTable();
alert(response.isError());
for(var i=0; i< dataTable.getNumberOfRows();i++){
var hrefval = dataTable.getValue(i,0).toString();
var arr = dataTable.getValue(i,1).toString().split(" ");
var latlng = new google.maps.LatLng(arr[0], arr[1]);
var marker = new google.maps.Marker({
position: latlng,
map:mapMain
});
markers.push(marker);
}
mc.addMarkers(markers);
}
This encrypted id is not valid:
1IagEEylcnbuPygCES70ipnvb9q0C5OgmGPNyx9o1
https://www.google.com/fusiontables/DataSource?docid=1IagEEylcnbuPygCES70ipnvb9q0C5OgmGPNyx9o1
I'm currently use a new system for my weather website and I'm getting the following error:
Uncaught TypeError: Cannot read property '__e3_' of undefined
Xe%7Bmain,places,weather%7D.js:18
Ve%7Bmain,places,weather%7D.js:21
P.addListener%7Bmain,places,weather%7D.js:18
T.(anonymous function).bindTo%7Bmain,places,weather%7D.js:27
initializejavascript.js:109
(anonymous function)javascript.js:4
f.Callbacks.ojquery.min.js:2
f.Callbacks.p.fireWithjquery.min.js:2
e.extend.readyjquery.min.js:2
c.addEventListener.B
Here's the content in my javascript.js file which I include in my header.php (<script src="javascript.js" type="text/javascript"></script>):
$(document).ready(function() {
initialize();
});
var elevator;
var geocoder;
var map;
function initialize() {
// KONFIGURATION: Geocoding
geocoder = new google.maps.Geocoder();
// KONFIGURATION: Filnamn
var weatherdata = 'fetch-information/fetch-weatherdata.php';
// KONFIGURATION: Datum
var date = new Date();
var datetime = date.getFullYear() + '-' +
(date.getMonth() < '10' ? '0' + date.getMonth() : date.getMonth()) + '-' +
(date.getDay() < '10' ? '0' + date.getDay() : date.getDay()) + ', ' +
(date.getHours() < '10' ? '0' + date.getHours() : date.getHours()) + ':' +
(date.getMinutes() < '10' ? '0' + date.getMinutes() : date.getMinutes()) + ':' +
(date.getSeconds() < '10' ? '0' + date.getSeconds() : date.getSeconds());
// KONFIGURATION: Hämta adress
var address = 'Karlstad, Sverige';
// KONFIGURATION: Inställningar för kartan
var myOptions = {
streetViewControl: false,
overviewMapControl: true,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// MOLNAKTIVITET
var cloudLayer = new google.maps.weather.CloudLayer();
cloudLayer.setMap(map);
/**********************************************
** THE CODE BELOW IS CAUSING THE ERROR **
**********************************************/
// HÖJD ÖVER / UNDER HAVSYTAN
elevator = new google.maps.ElevationService();
google.maps.event.addListener(map, 'click', getElevation);
/* ** ** ** ** ** */
// GOOGLE PLACES API
var input = document.getElementById('googlemaps-search');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
alert(place.geometry.location);
});
/**********************************************
** THE CODE ABOVE IS CAUSING THE ERROR **
**********************************************/
/* ** ** ** ** ** */
// GEOCODING
geocoder.geocode({'address' : address}, function(results, status) {
// KONTROLL
if(status == google.maps.GeocoderStatus.OK) {
// KONFIGURATION: Ta bort ( och ) före och efter koordinaterna
var old_latlong = '' + results[0].geometry.location + '';
var new_latlong = old_latlong.substring(1, old_latlong.length - 1).replace(' ', '');
// CENTERRING
map.setCenter(results[0].geometry.location);
// MARKERING: Adress
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
// AJAX: Hämta den angivna filen
$.ajax({
url: weatherdata + '?coordinates=' + new_latlong,
success: function() {
console.log(datetime + ': Hämtningen av väderprognosen och den övriga informationen lyckades');
$('.content-search').show();
$('#load-weather').load(weatherdata + '?coordinates=' + new_latlong);
},
error: function() {
console.error(datetime + ': Hämtningen av väderprognosen och den övriga informationen misslyckades');
$('#load-weather').hide();
$('.content-search').hide();
$('#message-error').show();
}
});
// KONTROLL
} else {
// FELMEDDELANDE
alert('Kunde inte hämta data på grund av följande fel: ' + status);
}
});
/* ** ** ** ** ** */
// KARTA
var map = new google.maps.Map(document.getElementById('weather-map'), myOptions);
}
/** ** ** ** ** ** ** ** ** ** ** ** **/
function getElevation(event) {
var locations = [];
var clickedLocation = event.latLng;
locations.push(clickedLocation);
var positionalRequest = {
'locations': locations
}
elevator.getElevationForLocations(positionalRequest, function(results, status) {
if(status == google.maps.ElevationStatus.OK) {
var s = results[0].elevation;
if(results[0]) {
if(('' + parseInt(s)).charAt(0) == '-') {
$('#elevation').html('Cirka ' + number_format(('' + parseInt(s)).substring(1)) + ' meter under havsytan');
} else {
$('#elevation').html('Cirka ' + number_format(parseInt(s)) + ' meter över havsytan');
}
} else {
alert('Inget resultat hittades');
}
} else {
alert('Det gick inte att hitta höjdskillnaden på grund av följande: ' + status);
}
});
}
The problem is that the system is quite the same as in my previous system and I have the same "code structure" on both of them and still I'm getting this error message on the new system. I don't know why I'm getting it so I'm asking you know: how can I fix my problem?
Thanks in advance.
When I moved the map definition to a point before the marked buggy code, it worked. I added the var map = new google.map.Map to right after the map options.
var myOptions = {
streetViewControl: false,
overviewMapControl: true,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('weather-map'), myOptions);
// MOLNAKTIVITET
var cloudLayer = new google.maps.weather.CloudLayer();
cloudLayer.setMap(map);
/**********************************************
** THE CODE BELOW IS CAUSING THE ERROR **
**********************************************/
// HÖJD ÖVER / UNDER HAVSYTAN
elevator = new google.maps.ElevationService();
google.maps.event.addListener(map, 'click', getElevation);