GLatLngBound from variables in javascript - javascript

I have images to overlay on google maps by using checkboxes. I made this script to not create the separate individual script for each overlay but it returns the error of proprty not supported in main.js of google maps api. However, i tried getting the output value in javascript alert and it returns the values as expected. Could anyone help please?
Here is the script.
function shImg(url,lat,lng) {
var lat_ = "new GLatLng(" + lat + ")";
var lng_ = "new GLatLng(" + lng + ")";
var latlng = lat_ + ", " + lng_;
var ticked_ = document.getElementById(url);
var boundaries_ = "new GLatLngBounds(" + latlng + ")";
var imgurl_ = "http://www.mywebsite.com/" + url + ".jpg";
imageOverlay_ = new GGroundOverlay(imgurl_, boundaries_);
map.addOverlay(imageOverlay_);
if (!ticked_.checked) {
map.clearOverlays();
// imageOverlay_=null;
}
else {
alert(boundaries_);
imageOverlay_.show();
}
}

The GLatLng constructor takes two arguments, a latitude and a longitude. Similarly GlatLngBounds takes two arguments, a GlatLng for the south west corner and one for the north east. See the api docs for more info.
Lastly why are you doing string concatenation all over the place? For example "new GLatLng(" + lat + ")"; should be new GLatLng(lat,lng);

Related

Google Map Loading issue in cordova ios

When I open Google Maps using google map URL for the first time(if google map is not running in background) direction will not show. If google map is running in background then direction will show properly. I am working on Cordova, in android, this issue is not there but in iOS, I am getting this issue.
My code is:
I used all these URL but it's not working in iOS if Google Maps is not running in the background.
var mapLocationUrl = "https://maps.google.com/maps?saddr=current location&daddr=" + lat + "," long;
var mapLocationUrl = "https://www.google.com/maps/dir/?api=1&destination=" + lat + "," + long + "&travelmode=driving";
var mapLocationUrl = "maps://maps.google.com/maps?daddr=" + lat + "," + long + "&ll=";
var mapLocationUrl = "comgooglemaps://?saddr=&daddr=" + lat + "," + long;
var mapLocationUrl = "https://maps.google.com/maps?origin=My Location" + "&daddr=" + lat + "," + long;
var mapLocationUrl = "https://maps.google.com/maps?daddr=" + lat + "," + lng;
window.open(encodeURI(mapLocationUrl), '_self', 'location=yes');
window`.open(encodeURI(mapLocationUrl), '_system', 'location=yes');
It looks like this may be related to issue 142856429 in Google’s Issue Tracker. I recommend you star the issue to get updates on its progress.
Edit: The issue is now fixed as per the recent comment on the tracker.

Location and weather based image search API for weather app

I am making a basic web-based weather app, which detects the current weather conditions in the user's location. My current code so far does work, but is missing an important feature - I want the background of the web page to change according to the user's location and weather conditions. For instance - if a user is in New York and the weather is sunny, I would like to display any New York based popular image(ex: Times Square) along with sunny skies as the body background. I've searched several APIs but haven't found any that meets my needs.
In my current code, I'm using IPInfo.io to get the user's location and OpenWeatherMap to get the weather conditions.
This pen has my code (NOTE - code for units hasn't been added yet), and here's the JS bit -
var lat = 0.0,
lon = 0.0;
var testURL = 'http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=2de143494c0b295cca9337e1e96b00e0';
var myURL = 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&appid="ae0acb60e8db4952e081c2fb470a1b23"';
var city = '',
state = '',
country = '',
postal = 0;
//if (navigator.geolocation) {
// /* geolocation is available */
// navigator.geolocation.getCurrentPosition(function (position) {
// lat = position.coords.latitude;
// lon = position.coords.longitude;
// console.log("Latitude = " + lat);
// console.log("Longitude = " + lon);
//
// display(position.coords.latitude, position.coords.longitude);
// });
//
//} else {
// /* geolocation IS NOT available */
// $("#jumbotron").html("geolocation not available");
//
//}
//get co-ordinates using ipinfo.io
$.getJSON('http://ipinfo.io', function (data) {
console.log(data);
var loc = data.loc;
lat = loc.split(",")[0];
lon = loc.split(",")[1];
display(lat, lon);
city = data.city;
state = data.region;
country = data.country;
postal = parseInt(data.postal, 10);
})
function display(x, y) {
$("#pos1").html("<b>" + x + "</b>");
$("#pos2").html("<b>" + y + "</b>");
}
//function to calculate wind direction from degrees
function degToCompass(num) {
//num = parseInt(num, 10);
console.log("Inside degtocompass = " + num);
var val = Math.floor((num / 22.5) + 0.5);
var arr = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"];
return arr[(val % 16)];
}
//function to return current temperature
function convertTemp(currTemp) {
//get celsius from kelvin
return Math.round(currTemp - 273.15);
}
$("button").click(function () {
console.log("In Latitude = " + lat);
console.log("In Longitude = " + lon);
//prepare api call
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&appid=ae0acb60e8db4952e081c2fb470a1b23',
//url: testURL,
type: 'GET', // The HTTP Method, can be GET POST PUT DELETE etc
data: {}, // Additional parameters here
dataType: 'json',
success: function (data) {
console.log(data);
//---------get the clipart---------------
var picLink = 'http://openweathermap.org/img/w/';
var picName = data.weather[0].icon;
picLink += picName + ".png";
$("#picture").empty().append('<img src="' + picLink + '">');
//----------get the temperature-----------
var curTemp = convertTemp(data.main.temp);
console.log("Current temp = " + curTemp);
//$("#temp").empty().append("<b>" + curTemp + "</b>");
$("#picture").append("<b>" + curTemp + "</b>");
//----------get the place----------------------
var area = city + ", " + state + ", " + country;
$("#area").empty().append("<b>" + area + "</b>");
//----------get weather conditions------------
$("#conditions").empty().append("<b>" + data.weather[0].description + "</b>");
//----------get wind speed------------
//get wind direction
var windSpeed = degToCompass(data.wind.deg);
//add wind speed
windSpeed += ' ' + data.wind.speed;
//display wind speed
$("#wind-speed").empty().append("<b>" + windSpeed + "</b>");
},
error: function (err) {
alert(err);
},
beforeSend: function (xhr) {
//xhr.setRequestHeader("X-Mashape-Authorization", "32ROUuaq9wmshfk8uIxfd5dMc6H7p1lqdZSjsnXkB5bQtBteLK"); // Enter here your Mashape key
}
});
});
Well... First of all there is no need to use WebServices, but you can't do it without any API. As I can see you use openweathermap API . As far as I know this API returns both longitude and latitude, so you can use these values as input to another request to a photo API (like flickr) to get the image you want. Moreover openweathermap API returns city name which can make your photo request even more accurate.

Looping through Google Places reviews array and getting value from callback function

I'm using the google places JavaScript API to get place details.
I am encountering two issues to do with JavaScript:
The first is extracting user reviews from the place.reviews array
I can get the place.name, place.phone, and place.formatted_address values but I am unable to retrieve the reviews from the place.reviews array.
I found some sample code on the link below to loop through the reviews array but I can't get it to work. I get script errors for example with the keyword forEach.
Google Places JS API Show Reviews
Is there an easy way to retrieve the values from the reviews array?
These are the script declarations at the top of my HTML document:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script>
The Second
I am creating a simple search app so I can view what's around me. I would like to add the distance and time from the start location to the venue the user clicks on i.e. 'London Bridge = 1 km, 10 mins'.
I can get the time and distance values using the Google matrix distance API using a callback function but I don't know how then to pass the values to the main part of my code.
I have had a look at some answers on here but I am still confused about how callback functions work:
function createMarkers(results, PlaceSearchStatus) {
var resultcontent = ''; //stores place results to be displayed on map
var resultdiv = document.getElementById('searchresults');
if (PlaceSearchStatus == google.maps.places.PlacesServiceStatus.OK) {
// if we have found something - clear map (overlays)
clearOverlays();
// and create new markers by search result
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
//use the Distance Matrix API to get the distance between this venue and start location
/distancematrix#distance_matrix_responses
var DistanceService = new google.maps.DistanceMatrixService();
var origin1 = new google.maps.LatLng(document.getElementById('lat').value, document.getElementById('lng').value);
var destination1 = results[i].geometry.location;
DistanceService.getDistanceMatrix({
origins: [origin1],
destinations: [destination1],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
function callback(response, DistanceMatrixStatus) {
if (DistanceMatrixStatus != google.maps.DistanceMatrixStatus.OK) {
alert('Distance matrix API Error was: ' + DistanceMatrixStatus);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
//getting the distance value gives more accurate results than the text value but not using that
//alert(results[i].distance.value + ", " + results[i].duration.value);
//get the time and distance to this location from our start location
// Need to fix. this isn't working as this is inside a callback function.
var TimeAndDistance = results[i].distance.text + ", " + results[i].duration.text;
}
}
} // end of distance matrix code
//concatonate the accessible search results and add on the time and distance to the place name
resultcontent += '<p> <h2>' + '<div <input id=\"button2\" type=\"button\" class=\"button\" value=\"' + results[i].place_id + '\" onclick=\"GetIndividualPlaceDetails(this);\">' + results[i].name + '</div> </h2>';
Thanks,
Tom
The following code works for accessing the reviews and I'm using another work around for my second question:
len = place.reviews.length;
for (i=0; i<len; ++i) {
resultcontent += place.reviews[i].rating + ' stars';
resultcontent += ', On ' + place.reviews[i].time + ' ' + place.reviews[i].author_name + ' said:';
if (!!place.reviews[i].text) resultcontent += '<br />' + place.reviews[i].text;
}
}

Google Maps Reloads again and the Markers disappear when i click a button in Asp.net web application

There's a small issue that i'm facing.
Part 1:
A little insight on what i'm trying to do.
Window.onload [in javascript] calls a function which displays the googlemaps nothing else.
Then on click of a button the latitude & longitude are read from the MySQL database, this code is written in C# code behind.
And from C# i call a javascript function with those latitude & longitude as parameters.
Now the javascript function Should place a marker on the received parameters, instead it reloads the googlemap and i don't see any Marker!
Part 2: I want to call a javascript again and again from a while loop to send the latest latitude and longitude as long as there is data in the MySQL table.
//The While Loop reads a row, and calls the javascript function !But for some reason the Javascript function gets called only once.
while(read.Read())
{
id= read["ID"].ToString();
lat = read["latitude"].ToString();
longitude = read["longitude"].ToString();
freq=read["frequency"].ToString();
array_ID.Add(Convert.ToInt32(id));
array_lat.Add(Convert.ToDouble(lat));
array_lon.Add(Convert.ToDouble(longitude));
array_freq.Add(Convert.ToInt32(freq));
string[] myarr = { id, lat, longitude, freq };
javascriptfunction_markers(myarr);
}
public void javascriptfunction_markers(string[] myarray_data)
{
StringBuilder javascriptFunction = new StringBuilder();
javascriptFunction.Append("qasim(");
javascriptFunction.Append("'" + myarray_data[0].ToString() + "',");
javascriptFunction.Append("'" + myarray_data[1].ToString() + "',");
javascriptFunction.Append("'" + myarray_data[2].ToString()+ "',");
javascriptFunction.Append("'" + myarray_data[3].ToString()+ "');");
Page.ClientScript.RegisterStartupScript(Page.GetType(), "OnLoadCall", javascriptFunction.ToString(), true);
}
the string built here looks like on a sample data :
qasim('1','33.2358','72.4560',5);
the javascript function 'qasim' in .aspx is :
function qasim(id,lat,lon,freq)
{
var ltlngx = [];
var x = id.toString();
var x1 = lat.toString();
var x2 = lon.toString();
var x3 = freq.toString();
alert("Function ID : " + x +" Lat: "+ x1 + " Lon: " + x2 +"Freq: "+ x3);
count = count + 1;
alert("Called times " + count.toString());
var xx = parseFloat(lat);
var yy = parseFloat(lon);
ltlngx.push(new google.maps.LatLng(xx, yy));
alert("Lat,lng is " + ltlngx[0]);
map.setCenter(ltlngx[0]);
marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: ltlngx[0],
icon: 'images/map-pin.png'
});
var i=0;
(function (i, marker) {
var xx = marker.position.toString();
google.maps.event.addListener(marker, 'click', function () {
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
infowindow.setContent('Location info:<br/><br/>Lat & Lng:' + xx + "<br/>" + " ID : "+x+" Freq: "+x3);
infowindow.open(map, marker);
});
})(i, marker);
}

Javascript: Initializing a variable from a string?

I am working in Google Maps and have three+ tile overlays to create. An example:
Tile Overlay
var parkingOptions = { //Parking Overlay
getTileUrl: function(coord, zoom) {
return "/maps/tiles/tilesparking/" + zoom + "_" + coord.x + "_" + coord.y + ".png";
},
tileSize: new google.maps.Size(256, 256)
};
var parkingMapType = new google.maps.ImageMapType(parkingOptions);
However, to avoid 404 errors by missing tiles outside of my mapping range, my code is a little more complex; thus, I intended to make a loop where a specific keyword assigned to each overlay (here given as "parking") would be inserted into the above code. Thus:
For Loop
var tileNames = ["base", "parking", "access"];
for (var i = 0; i < tileNames.length; i++) {
//insert Tile Overlay code here
};
However, I have one particular issue: I can not find a way to take the string from the tileNames array and use them in initializing the two variables in the Tile Overlay code. Ideally, I would like to achieve something like this:
Attempt 1
var tileNames[1] + "Options" = { //ideally: var parkingOptions = {
//insert remaining code
};
However this doesn't work, nor did I really expect it to. Neither would trying to create those full strings and trying to insert it into the initialization:
Attempt 2
var newOptions = tileNames[1] + "Options";
var newOptions = {
//insert remaining code
};
Thus, is there a way to do place a string into initializing variables?
Note: I have included my own alternative solution to the problem as an answer. It should work, but it destroys the names of the variables and replaces it with a nondescript array variable. I preferably would like to retain a descriptive variable name as they are used often in adding and hiding the overlays in the resulting code.
Solution For this question anyways...
var tileNames = ["beloit", "parking", "access"];
var mapType = {};
for (var i = 0; i < tileNames.length; i++) {
var tileOptions = {
getTileUrl: function(coord, zoom) {
return "/maps/tiles/tiles" + tileNames[i] + "/" + zoom + "_" + coord.x + "_" + coord.y + ".png";
},
tileSize: new google.maps.Size(256, 256)
};
mapType[tileNames[i]] = new google.maps.ImageMapType(tileOptions);
};
The other part of the puzzle, the "tileNames[i]" in the getTileUrl function is undefined because the function wants it when it is executed rather than placing the name string into the function; however, that is a new question to be found here: Javascript: Making a variable static when defining a function in a loop?
you can't do this:
var tileNames[1] + "Options" = {
//insert remaining code
};
but you can do this:
window['a'] = 'b';
alert(a); // shows 'b'
or if you are in a function
this['a'] = 'b';
EDIT:
var obj = {};
obj.a = 'a';
// obj.a == obj['a']
alert(obj['a']) // alerts a
Now, I don't know if the above is indeed possible (and I would somewhat prefer it did as I'll explain below), but in drafting this question, the various other Q/A I read beforehand began to make more sense. Their general message: "use arrays":
Possible Solution
(Edited; should be usable now.)
var tileNames = ["beloit", "parking", "access"]; //Would be used more than once.
var tileMapType = [];
for (var i = 0; i < tileNames.length; i++) {
var tileOptions = {
getTileUrl: function(coord, zoom) {
return "/maps/tiles/tiles"+tileNames[i]+"/" + zoom + "_" + coord.x + "_" + coord.y + ".png";
},
tileSize: new google.maps.Size(256, 256)
};
tileMapType[i] = new google.maps.ImageMapType(tileOptions);
};
The only issue with this approach is that, in the code which follows, I have to place these MapTypes into the map as well as toggle them as visible and invisible, and using the nondescript tileMapType[x] to do so hinders overall readability. (Perhaps this doesn't matter as much as I think it does, but still. >.>)
Assuming I've understood your question, you can encapsulate your tiles in an object and refer to the layer by the name you provide:
var tileNames = ["base", "parking", "access"];
var Tiles = {};
for (var i = 0; i < tileNames.length; i++) {
Tiles[tileNames[i]] = makeOverlay(tileNames[i], coords, zoom);
};
//iterate the maps
for (var tile in Tiles)
alert(Tiles[tile].someGoogleMapPropery)
//individually
alert (Tiles.base.someGoogleMapPropery)
alert (Tiles.parking.someGoogleMapPropery)
//or
alert (Tiles["access"].someGoogleMapPropery)
function makeOverlay(name, coords, zoom) {
return new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return "/maps/tiles/tiles" + name + "/" + zoom + "_" + coord.x + "_" + coord.y + ".png";
},
tileSize: new google.maps.Size(256, 256)
});
}​
It's possible to read variables like that using eval(), but not set them.
Example:
var a = "b";
var b = "c";
eval (a); // returns "c"

Categories

Resources