How can I make this happen when page loads? - javascript

I work as an intern with Ruby on Rails and yesterday I had to do something with Javascript (my javascript skills ARE AWFUL, I DON'T EVEN HAVE SKILLS with IT).
I implemented current location feature in a project, but I'd like to do it another way... the thig is kinda done, take a look:
function geolocationSuccess(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var geocoder = new google.maps.Geocoder();
var latlng = {lat: latitude, lng: longitude};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[0]){
var user_address = results[0].formatted_address;
document.getElementById("current_location").innerHTML = user_address;
}else {
console.log('No results found for these coords.');
}
}else {
console.log('Geocoder failed due to: ' + status);
}
});
}
function geolocationError() {
console.log("please enable location for this feature to work!");
}
$(document).on("ready page:ready", function() {
$("#current-location").on("click", function(event) {
event.preventDefault();
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
} else {
alert("Geolocation not supported!");
}
});
});
All right, I know it all happens when I click the button with Id="current-location", but I'd like it to happen automatically when the page loads, how can I do it?

Simply insert the code you want executed inside of a $(document).ready( block:
$(document).ready(function() {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
} else {
alert("Geolocation not supported!");
}
});
On a side note, I would recommend not naming a function variable event since event is a keyword. The standard convention for passing event to a function is to use e. For example:
$('#someId').on('click', function(e) {
e.preventDefault();
//do something
});

Related

angular too much recursion error in firefox

I am working on an application and need to convert an address supplied by user to lat lng and update a google map. I am using angular js version 1.0.0 Problem is in firefox i keep getting a too much recursion error.
app.controller("BasicMapController", function($scope, $timeout){
.......
angular.extend($scope, {
.......
checking_address: false// curently trying to get lat long from address
});
......
I had to create an ngBlur directive since 1.0.0 didn't have it and upgrading is not an option since too much other code breaks.
app.directive('ngBlur', function() {
return function( scope, elem, attrs ) {
elem.bind('blur', function() {
scope.$apply(attrs.ngBlur);
});
};
});
On my page i add ng-blur="onblur_()" to the relevant text area and then in my controller i define the relevant function:
$scope.onblur_ = function ($event) {
if ($scope.checking_address)
return;
var map_scope = angular.element($('.google-map')).scope();
var address = document.getElementById("id_address").value;
if ( !! !address)
return;
$scope.checking_address = true;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map_scope.map._instance.panTo(results[0].geometry.location);
if ($scope.markers[0] == undefined) {
$scope.markers[0] = new google.maps.Marker({
map: map_scope.map._instance,
position: results[0].geometry.location
});
} else
$scope.markers[0].setPosition(results[0].geometry.location);
}
$scope.checking_address = false;
});
}
The code works fine in Opera and Chromium. Any ideas on what could be wrong or how i could get around the problem?

Geocoder not returning results

This is my first JavaScript I have tried to put together but I am not having a lot of luck.
This is what the script should do: Geocode an address either by clicking on an autosuggested location or by clicking search button if we do not have the result already from clicking autosuggestion. Then submit the form.
I am not having much luck, it seems I have mucked up my bracketing on the script because no matter what I do it complains about exceptions.
This is my code:
geocode();
// SET COOKIE FOR TESTING PURPOSES
$.cookie("country", "US");
// GEOCODE FUNCTION
function geocode() {
var coded = false;
var input = document.getElementById('loc');
var options = {
types: ['geocode']
};
var country_code = $.cookie('country');
if (country_code) {
options.componentRestrictions = {
'country': country_code
};
}
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
processLocation();
});
// ON SUBMIT - WORK OUT IF WE ALREADY HAVE THE RESULTS FROM AUTOCOMPLETE FUNCTION
$('#searchform').on('submit', function(e) {
e.preventDefault();
if(coded = false;) {
processLocation();
}
else {
$('#searchform').submit();
}
});
// CHECK TO SEE IF INPUT HAS CHANGED SINCE BEING GEOCODED
// IF "CODED" VAR IS FALSE THEN WE WILL GEOCODE WHEN SEARCH BUTTON HIT
$("#loc").bind("change paste keyup", function() {
var coded = false;
});
};
// GEOCODE THE LOCATION
function processLocation(){
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('loc').value;
$('#searchform input[type="submit"]').attr('disabled', true);
geocoder.geocode({
'address': address
},
// RESULTS - STORE COORDINATES IN FIELDS OR ERROR IF NOT SUCCESSFUL
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var coded = true;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
} else {
var coded = false;
$('#searchform input[type="submit"]').attr('disabled', false);
alert("We couldn't find this location")
}
});
}
Where have I gone wrong?
PS: Because this is my first script, I am happy to receive feedback if I have made any poor choices in the design of it. I really want to make my first script as cleanly coded as possible.
There is an syntax error
if(coded = false;) {
should be
if(coded == false) {
Checking the console would have told you such a thing and also the place WHERE the error occured.... Here's your fixed fiddle

Google Map Autosuggest - Trigger Geocode on click of autosuggest

Currently when you click on the autosuggest suggestion in the location field it just loads it into the input box. I want to make an adjustment to it, so when you click on the result in the autosuggest box, not only does it load its value into the input box but it also triggers the geocode. I cant get my head around how I would do this though, so I would appreciate some help.
This is the code: http://jsfiddle.net/njDvn/130/
<!-- Geocode -->
$(document).ready(function () {
var GeoCoded = { done: false };
autosuggest();
$('#myform').on('submit', function (e) {
if (GeoCoded.done) return true;
e.preventDefault();
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());
GeoCoded.done = true;
$('#myform').submit();
} else {
console.log("Geocode failed: " + status);
//enable the submit button
$('#myform input[type="submit"]').attr('disabled', false);
}
});
});
});
And the autosuggest:
<!-- AutoSuggest -->
function autosuggest() {
var input = document.getElementById('location');
var options = {
types: [],
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
}
What you could do instead is use only Places API library and simply listen for place_changed event like in this sample here:
https://developers.google.com/maps/documentation/javascript/places#getting_place_information
You can get the Geocode using: place.geometry.location

Google Maps geocode inside a listener

I don't know why the r1 variable is undefined.
The 'latLng': mEvent.latLng thing is working OK on other functions...
<!-- API V3 --> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
....
.....
....
google.maps.event.addListener(map, 'click', function(mEvent) {
var geo1 = new google.maps.Geocoder();
geo1.geocode( { 'latLng': mEvent.latLng }, function(results, status) {
if ( status == google.maps.GeocoderStatus.OK )
{
var r1 = results[0].formatted_address;
}
else
{
var r1 = '?';
}
});
//do things with mEvent.latLng and r1...
Variable r1 is most probably undefined because it's out of scope. You need to move it's declaration up a bit. E.g.:
google.maps.event.addListener(map, 'click', function(mEvent) {
var geo1 = new google.maps.Geocoder();
var r1;
geo1.geocode( { 'latLng': mEvent.latLng }, function(results, status) {
if ( status == google.maps.GeocoderStatus.OK )
{
r1 = results[0].formatted_address;
}
else
{
r1 = '?';
}
});
//do things with mEvent.latLng and r1...
If you still find some problem use Firebug (in Firefox) or built in debuggers in other browsers. You can insert "debugger;" keyword to stop at some line when a debugger is active. You will then be able to check what variables are available.

Google Map V3 - Getting geoPostition data into hidden field

I have a Google map that uses W3C geoLocation to get a persons location. I would like to know how to get the lat and lng of their initial position into a hidden field.
// Try W3C Geolocation (Preferred)
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
// Try Google Gears Geolocation
} else if (google.gears) {
browserSupportFlag = true;
var geo = google.gears.factory.create('beta.geolocation');
geo.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeoLocation(browserSupportFlag);
});
// Browser doesn't support Geolocation
} else {
browserSupportFlag = false;
handleNoGeolocation(browserSupportFlag);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag === true) {
alert("Geolocation service failed.");
initialLocation = newyork;
} else {
alert("Your browser doesn't support geolocation. We've placed you in beautiful Minneapolis.");
initialLocation = siberia;
}
map.setCenter(initialLocation);
}
Just like the approach I used in this question:
In the getCurrentPosition method:
populateInputs(initialLocation);
Where function looks like:
function populateInputs(pos) {
document.getElementById("t1").value=pos.lat()
document.getElementById("t2").value=pos.lng();
}
Where t1 and t2 are your hidden fields
Just before (the two places) you get initialLocation, you're given the lat and longitude (as: position.coords.latitude,position.coords.longitude or position.latitude,position.longitude).
just call a function to set a hidden field at that point (passing in the lat and long). Something like:
var setHiddenField = function(lat, long) {
document.forms[0].hiddenLatField.value = lat;
document.forms[0].hiddenLongField.value = long;
}
...I'm assuming only 1 form on your page, but you should be easily able to tweak this.

Categories