I'm trying to get lng and lat coordinates of the Google Maps API by the next example http://jsbin.com/inepo3/7/edit. I expect a 'success' popup, but it keeps showing the 'Error' popup.
The google maps-request gives the correct json feedback (checked by firebug).
<script type="text/javascript">
$().ready(function() {
$.fn.getCoordinates=function(address){
$.ajax(
{
type : "GET",
url: "http://maps.google.com/maps/api/geocode/json",
dataType: "jsonp",
data: {
address: address,
sensor: "true"
},
success: function(data) {
set = data;
alert(set);
},
error : function() {
alert("Error.");
}
});
};
$().getCoordinates("Amsterdam, Netherlands");
});
</script>
Does anyone know how to fix this issue?
Regards,
Guido Lemmens
EDIT
I found a bether solution using the Google Maps Javascript API combined in jQuery:
<script type="text/javascript">
$().ready(function() {
var user1Location = "Amsterdam, Netherlands";
var geocoder = new google.maps.Geocoder();
//convert location into longitude and latitude
geocoder.geocode({
address: user1Location
}, function(locResult) {
console.log(locResult);
var lat1 = locResult[0].geometry.location.lat();
var lng1 = locResult[0].geometry.location.lng();
$("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</p>");
});
});
</script>
Google Map API V3 makes it harder for external libraries to work with JSONP. Here is a blog post about it.
JSONP and Google Maps API Geocoder Plus A Fix w/ jQuery
An alternative way of getting Geocoding is to use the Google Map V3 API Geocoder Service. Here is an example that i helped a person that was having a similar issue as you to replace his JSONP to use Google Map V3 Geocoder Service. Take a look at this JSFiddle Demo:
This is basically the core. We basically use twitter to get the tweet's address (IE. London, Madrid or Georgia etc) and convert the actual address into LatLng using Google Map's Geocoder Service:
$.getJSON(
url1, function(results) { // get the tweets
var res1 = results.results[0].text;
var user1name = results.results[0].from_user;
var user1Location = results.results[0].location;
// get the first tweet in the response and place it inside the div
$("#last-tweet1").html(res1 + "<p>from: " + user1name + " (" + user1Location + ")</p><p>");
//convert location into longitude and latitude
geocoder.geocode({
address: user1Location
}, function(locResult) {
console.log(locResult);
var lat1 = locResult[0].geometry.location.lat();
var lng1 = locResult[0].geometry.location.lng();
$("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</p>");
});
});
Related
I'm building a web-page that shows the weather. I would like for it to be able to use geolocation, as well as the option to manually input a location to pull weather information. I've got the geolocation working fine, but am unsure as to how to add an additional input using either a city or zipcode.
Here's my relevant code:
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function(position) {
loadWeather(position.coords.latitude + ',' + position.coords.longitude);
});
} else {
loadWeather("", "1062617");
}
function loadWeather(location, woeid) {
$.simpleWeather({
location: location,
woeid: woeid,
unit: 'f',
success: function(weather) {
$(".weather-text").html(weatherText[weather.code]);
$(".weather-icon").html('<i class="icon-' + weather.code + '"></i>');
$(".weather-stats").html('<ul><li><strong>'+weather.city+', ' +weather.region+ '</strong></li>');
$(".weather-stats").append('<li>'+ weather.temp + '°F / '+ weather.alt.temp +'°C</li></ul>');
},
error: function(error) {
$("#weather").html('<p>' + error + '</p>');
}
});
}
I'm pretty new to javascript & jquery, so I understand how to make an input box with HTML but am unsure how to use the user input data to then retrieve the associated weather data.
The getCurrentPosition gives you access to the position interface which then gives you the coordinates. So your if statement results in a latitude and longitude based on the device's Geolocation. In order to get this same information from a user's input (latitude and longitude), you need to convert the input (could be City, State or a full address) to coordinates. I recommend using Google maps API to convert that user input.
Once converted, you can then pass the lat and long to loadWeather(). Here's an example of a user's input (Address) converted:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
var address = jQuery('#address').val();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
jQuery('#coordinates').val(latitude+', '+longitude);
loadWeather(latitude + ',' + longitude);
}
});
</script>
<input id="address" type="text" placeholder="Enter City, State"/>
Of course you would use the above within proper context such as checking whether geolocation worked first or whenever a user actually enters their address. You might need a Google Maps API for this bit that should be easy to get.
Give it a shot, if stuck, check out this fiddle: jsfiddle
EDIT:
I grabbed Yahoo's Weather API endpoint and here is working fiddle:
https://jsfiddle.net/mjsgwq55/3/
I highly recommend logging variables so you can tell what time of data they contain. In your fiddle, you tried to access a property that doesn't exist in the object. Logging that would easily show you what to use.
EDIT: Just finished up the project. New link is up here! http://codepen.io/myleschuahiock/full/pyoZge/
I'm in the process of making a Weather Widget App for my Free Code Camp. Everything except the "city" is a static placeholder. I'm using the Open Weather Api, which makes us to a latitude and longitude. For debugging purposes, I placed the longitude and latitude of my area underneath the time placeholder.
My problem is that when I statically input the lat and lon on my API link, it works just fine. It returns "Mandaluyong City", a nearby city where I live:
http://api.openweathermap.org/data/2.5/weather?lat=14.603814400000001&lon=121.04907589999999&id=524901&APPID=ca8c2c7970a09dc296d9b3cfc4d06940
But when I do this, where I dynamically add mylatitude and mylongitude, to complete the API link:
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
I always get "Moscow" as my city.
Please take a closer look at my Javascript/JQuery code here!
http://codepen.io/myleschuahiock/pen/zqYzWm?editors=0010
Thank you very much! Much appreciated!
Easy solution for you.
Move the $.getJSON() into your if condition, why attempt to query the weather if the client blocks the location?
As Jaromanda X has pointed out:
navigator.geolocation.getCurrentPosition is asynchronous. So, you're calling $.getJSON before the location is actually determined.
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$('.geo').html(position.coords.latitude+ " " +position.coords.longitude);
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat="+position.coords.latitude+"&lon="+position.coords.longitude+"&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
});
});
}else{
$(".geo").html("Please turn on Geolocator on Browser.")
}
});
I hope this helps. Happy coding!
Added
getName(mylatitude, mylongitude);
and changed
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
});
to
function getName(mylatitude, mylongitude){
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
});
}
http://codepen.io/anon/pen/Yqzvbd?editors=0010
You can use third-party IP API that provides the name of the city. With use jQuery function $.getJSON()
var openWeatherMap = 'http://api.openweathermap.org/data/2.5/weather';
var APPID = 'APPID';
var ipAPI = 'http://ip-api.com/json/';
$.getJSON(ipAPI).done(function(location) {
$('.geo').html(location.lat + " " + location.lon);
$('.city').html(location.city);
$.getJSON(openWeatherMap, {
lat: location.lat,
lon: location.lon,
APPID: APPID
}).done(function(weather) {
$('#temperature').html(weather.main.temp - 273.15);
})
})
OpenWeatherMap provides the temperature in Kelvin on this I did weather.main.temp - 273.15 to get Celsius
how can I search by location(address).
I want to pass the location to my map. Now I have added lat, long.
Or is there a quick way to find out the lat and long with javascript?
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(40.0000, -98.0000), Here I want to just add the location for example Dublin, Ireland
mapTypeId: google.maps.MapTypeId.ROADMAP
}
http://jsfiddle.net/pc7Uu/346
Thanks for your help.
Best
It is called Geocoding, it is actually very easy to use, read the The Google Maps Geocoding API to get started, since you are using JavaScript you don't need an API_KEY so you can actually convert addresses to lat/lng values with requests like this:
https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA
You will get a JSON with the coordinates inside the "location" key, like this:
...
"location" : {
"lat" : 37.4220352,
"lng" : -122.0841244
},
...
There are changes from V2 to V3 (recommended). Here are both documentations in case you want use an specific version:
V3 API: http://code.google.com/apis/maps/documentation/geocoding/
V2 API: http://code.google.com/apis/maps/documentation/services.html#Geocoding
If you want autocomplete functionality and/or site name to lat/lng coordinates, check the Place Autocomplete Hotel Search example.
Google Maps Geocoding API is intended for that purpose, the below example shows how to set map center based on the provided address:
//Data
var cities = [
{
city : 'Toronto',
desc : 'This is the best city in the world!',
lat : 43.7000,
long : -79.4000
},
{
city : 'New York',
desc : 'This city is aiiiiite!',
lat : 40.6700,
long : -73.9400
},
{
city : 'Chicago',
desc : 'This is the second best city in the world!',
lat : 41.8819,
long : -87.6278
},
{
city : 'Los Angeles',
desc : 'This city is live!',
lat : 34.0500,
long : -118.2500
},
{
city : 'Las Vegas',
desc : 'Sin City...\'nuff said!',
lat : 36.0800,
long : -115.1522
}
];
//Angular App Module and Controller
angular.module('mapsApp', [])
.controller('MapCtrl', function ($scope) {
var mapOptions = {
zoom: 4,
//center: new google.maps.LatLng(40.0000, -98.0000),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
var setMapCenterByAddress = function(map,address) {
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: address
});
}
else {
console.log("Geocoding failed: " + status);
}
});
}
};
setMapCenterByAddress($scope.map,'Dublin, Ireland');
});
<script src="http://maps.googleapis.com/maps/api/js?key=&sensor=false"></script>
<script src="http://code.angularjs.org/1.2.25/angular.js"></script>
<script src="map.js"></script>
<style>
#map {
height:420px;
width:600px;
}
</style>
<div ng-app="mapsApp" ng-controller="MapCtrl">
<div id="map"></div>
</div>
I think your present code won't do what you are trying to do.
First, here's what the code needs to do, in plain English. I will explain each part later.
1. Send a request to the Google Geocoding API : This request will include the address you are trying to find lat&lng for. You will receive a response in the form of JSON, which you will parse to get the information you need.
2. Save the information (latitude and longitude) in a variable
3. Create a map, and use the lat&lng you found above as its center.
Okay, now here are the sources for the code. Don't worry, these code samples are very straightforward and you will easily understand what to do.
How to send the 'GET' request:
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
document.body.className = 'ok';
} else {
document.body.className = 'error';
}
}
};
request.open("GET", url , true);
request.send(null);
The http request for geocoding:
https://developers.google.com/maps/documentation/geocoding/intro#GeocodingRequests
Here is what the code will look like: (example)
var json = https://maps.googleapis.com/maps/api/geocode/json?address=1600+"ADD ADDRESS HERE"&key=YOUR_API_KEY;
var object = JSON.parse(json);
Then you can extract the lat&lng from this object.
After that, create a map using: (link) www.developers.google.com/maps/tutorials/fundamentals/adding-a-google-map
(Use the latitude and longitude you extracted above as the 'center' of the google map you will create)
I used this plugin it is very simple:
https://ubilabs.github.io/geocomplete/
alternative free service of geo location to coordinates you can use openstreet map, you can combine this with jquery autocomplete
http://nominatim.openstreetmap.org/search/
I wrote a small app to test out Google Map API and I noticed that my functions do not execcute in the expected order. Please take a look at my code below.
<!DOCTYPE html><htm><head><title></title>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"> </script>
<script>
//Global Variables
var lat, lng, _Address;
var geocoder = new google.maps.Geocoder();
function getReverseGeocodingData(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
// Make the Geocode request
geocoder.geocode({ 'latLng': latlng }, function (searchResults,searchStatus) {
if (searchStatus !== google.maps.GeocoderStatus.OK) {
alert("Your search yields " + searchStatus);
}
// Checking to see if the Geocode Status is OK before proceeding
if (searchStatus == google.maps.GeocoderStatus.OK) {
console.log(searchResults);
_Address = (searchResults[0].formatted_address);
alert("First time Address is displayed" + _Address);
}
});
}
function splitAddress() {
var addressArr = _Address.split(',');
//addressArr will be used later
}
// This function is called when the submit button is clicked
function SearchAddress() {
geocoder.geocode({ 'address': "77 Massachusetts Ave, Cambridge, MA 02139" }, function (searchResults, searchStatus) {
var location = searchResults[0].geometry.location;
lat = location.lat();
lng = location.lng();
getReverseGeocodingData(lat, lng);
alert("Second time Address is displayed" + _Address);
splitAddress();
});}
</script></head><body><div><input type="button" value="Submit" onclick="SearchAddress()"></div></body></html>
When I set a break point on the line alert("First time Address is displayed" + _Address), I can tell that this alert function executes before the line alert("Second time Address is displayed" + _Address).
However, the line alert("Second time Address is displayed" + _Address) appears as though it executes first and the value of _Address is undefined. So my question is if the second alert function executes after the first alert function, is Google Map API making an asynchronous request.
Yes, Google Maps API uses asynchronous requests when you call geocoder.geocode.
This is in the documentation.
Accessing the Geocoding service is asynchronous, since the Google Maps
API needs to make a call to an external server.
I have a simple page which makes two JQuery AJAX calls to get parameters and then it updates a google maps Lat and Lng,
For some reason after the two AJAX calls are made, the google map then seems to timeout and go Grey.
Anyone ever experienced this before or have any ideas as of why it would be doing this?
Thanks
var pclat;
var pclng;
var pc = document.forms[0]["postcode"].value;
$.get("get_latlong.php", { cp: pc, cord: "Lat" }, function(data){
alert("Lat: " + data);
pclat = data;
});
$.get("get_latlong.php", { cp: pc, cord: "Lng" }, function(data){
alert("Long: " + data);
pclng = data;
});
updateMap(pclat, pclng);
}
function updateMap(pclat, pclng){
var postcodeLL = new google.maps.LatLng(pclat, pclng);
map.panTo(postcodeLL);
marker.setPosition(postcodeLL);
marker.setMap(map);
}