I am using jQuery with the Google Maps API V3's Geocoder. The site user enters a location in the textbox and clicks on the submit button, which calls the code below to geocode the address given by the user into LatLng coordinates.
$(function(){
$("#searchbox_form #search_button").click(function(){
var address = $("#location").val();
var geocoder = new google.maps.Geocoder();
alert(address);
geocoder.geocode( { 'address': address}, function(results, status) {
alert("123");
if (status == google.maps.GeocoderStatus.OK) {
$("#user_lat").val(results[0].geometry.location.lat);
$("#user_lng").val(results[0].geometry.location.lng);
alert("lat: " + $("#user_lat").val());
alert("lng: " + $("#user_lat").val());
} else {
alert("asdasdasd");
alert(status);
}
});
});
});
However there is some problem. You will notice I placed several alert()s in the code. When 'Boston' is entered into the textbox and the submit button is clicked, only alert("address"); is executed showing Boston but alert("123") does not run. Did something go wrong somewhere?
Solution is to disable the submitting of the form :)
Check in any web - debugger whether any request is even made or not?
The code seems fine to me.
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.
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 am using Google maps to get address in mobile application. Code is working fine when there is an internet connection. If not then my app takes 1 minute to load or sometimes it shows an application error. This is due to loading a URL within the script, so I wanted to load my script asynchronously. Can anyone give me some logic to solve my issue, how do I rewrite the below script asynchronously?
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true">
function address()
{
var geocoder ;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
if (results[0])
{
var add= results[0].formatted_address ;
document.getElementById("location").innerHTML="Location : " + add ;
}
else
{
document.getElementById("location").innerHTML="No Results found " ;
}
}
else
{
//document.getElementById("location").innerHTML="Geocoder failed due to: " + status;
//alert("Geocoder failed due to: " + status);
}
});
}
This should do it:
jQuery.getScript('https://maps.googleapis.com/maps/api/js?sensor=true', address);
BTW, getScript() is a helper function for jQuery.ajax(). if you use the latter you can take more control and set more options, specifically a timeout parameter so it does not just spin for ever or the cache parameter so that you don't have to look it up all the time
A fiddle that's similar. Sorry fiddles can't use external resources directly so I have to create a simpler script request but you can see the callback is referencing the new javascript.
This is the code I am working from:
http://jsfiddle.net/njDvn/75/
var GeoCoded = {done: false};
$(document).ready(function(){
console.log('ready!');
autosuggest();
console.log($('#myform input[type="submit"]'));
$('#myform').on('submit',function(e){
if(GeoCoded.done)
return true;
e.preventDefault();
console.log('submit stopped');
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('location').value;
$('#myform input[type="submit"]').attr('disabled',true);
geocoder.geocode({
'address': address
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
//if you only want to submit in the event of successful geocoding, you can only trigger submission here.
GeoCoded.done = true;
$('#myform').submit();
} else {
console.log("Geocode was not successful for the following reason: " + status);
//enable the submit button
$('#myform input[type="submit"]').attr('disabled',false);
}
});
});
});
This works how I want BUT, I wanted to complete the geocode when someone clicks on the autocomplete. So, when they type something and click on a suggestion from the autosuggest list, it actually completes the geocode call when the click the result.
If anyone could tell me if this is possible I would really appreciate it, because I havent been able to figure out how to do it myself.
Autocomplete incorporates geocoding automatically. Example here.
Edit:
Here is the gist of that example:
The key lines for creating the autocomplete control are:
var input = document.getElementById('searchTextField');
var options = {
types: [],
componentRestrictions: {country: 'us'}
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
You also need to load the Places library:
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
and in your HTML:
<input id="searchTextField" type="text" size="50" value="">
By the way, you don't "add autocomplete to the geocoder".The Places Autocomplete class includes geocoding capabilities.
The address I have is a concatenated results[1].formatted_address retrieved from a database containing 6 numbers e.g 530456. I then geocoded it and placed a marker on a google map. This part is successful.
I now want to display the full address, results[0].formatted_address in a infowindow of the marker, so what I did was to reverse geocode the latLng of the marker to obtain the full address but caused the entire map to disappear. The way I did it is as such:
var address;
var eventwindow;
function codeAddress(postal) {
geocoder.geocode( {'address': postal + ", Singapore"}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
eventwindow = new google.maps.InfoWindow();
var markerE = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
});
address = getMarkerAddress(results[0].geometry.location);
google.maps.event.addListener(marker, 'click', function(){
if(eventwindow)
eventwindow.close();
eventwindow = new google.maps.InfoWindow({
content: address,
});
eventwindow.open(map,marker);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function getMarkerAddress(location) {
geocoder.geocode({'latLng': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if(results[0])
{
address = results[1].formatted_address.substring(10);
}
}
else {
alert("Geocoder failed due to: " + status);
}
});
I don't know if I'm doing this right and and not sure where I went wrong. Is there another way to this problem? If so how?
I don't know if I'm doing this right and and not sure where I went wrong. Is there another way to this problem? If so how?
If you know the "correct" address, use that. You haven't provided enough details of your application to make suggestions on how to do that. You can avoid the uncertainty of the geocoder by storing the coordinates that are returned from the geocoder in your database along with the address, then if you find an error, you can fix it.
This article on geocoding strategies might help.