I have form in my view that is made of checkboxes, some textfields and selects.
On the same page I have googlemap geocoder. The location lat&lng is saved in variables in javascript.
function geocodeAddress(geokodiranje, resultsMap) {
var address = document.getElementById('address').value;
var location = {};
geokodiranje.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
location.lattitude = results[0].geometry.location.lat();
location.longitude = results[0].geometry.location.lng();
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
lat = location.lattitude; //THIS IS MY LAT
lng = location.longitude; //THIS IS MY LNG
} else {
alert('Geocode failed for reason: ' + status);
}
});
}
And in my controller I have POST function to save form in database.
$input = Request::all();
Blogpost::create($input);
return redirect('other');
In my DB I have columns for lat and lng and I want to add variables and the problem is that I can't add this 2 variables into $input variable in my controller. Help me please! :)
you need to add 2 hidden field lat and lon in your form like :
<input type="hidden" name="lat" class="lat" />
<input type="hidden" name="lon" class="lon" />
And set value in js code like this way :
function geocodeAddress(geokodiranje, resultsMap) {
var address = document.getElementById('address').value;
var location = {};
geokodiranje.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
location.lattitude = results[0].geometry.location.lat();
location.longitude = results[0].geometry.location.lng();
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
lat = location.lattitude; //THIS IS MY LAT
lng = location.longitude; //THIS IS MY LNG
$('.lat').val(lat);
$('.lon').val(lng);
} else {
alert('Geocode failed for reason: ' + status);
}
});
}
Related
I'm using this code to get the current location of the user through google maps api and i am getting the location in the form of latitude and longitudes and getting the location in LatLng variable.
But after that when I am converting the latitude and longitude to an address then its not working.
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (p){
var LatLng = new google.maps.LatLng(p.coords.latitude,p.coords.longitude);
alert(LatLng);
alert(p.coords.latitude);
alert(p.coords.longitude);
var mapOptions = {
center: LatLng,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'LatLng': LatLng }, function (results, status){
alert(geocoder);
if (status == google.maps.GeocoderStatus.OK){
if (results[1]){
alert("Location: " + results[1].formatted_address);
}
}
});
Firstly as the commentator Parker told, jsp and java tags are irrelevant for your post. I removed it.
You should do the reverse geocoding. The process of doing the converse, translating a location on the map into a human-readable address, is known as reverse geocoding.
Please refer the below google map url for Reverse Geocoding.
See the below snippet of mapping lat & lan to location,
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
Let me know if it helps.
$(document).ready(function() {
var currgeocoder;
//Set geo location of lat and long
navigator.geolocation.getCurrentPosition(function(position, html5Error) {
geo_loc = processGeolocationResult(position);
currLatLong = geo_loc.split(",");
initializeCurrent(currLatLong[0], currLatLong[1]);
});
//Get geo location result
function processGeolocationResult(position) {
html5Lat = position.coords.latitude; //Get latitude
html5Lon = position.coords.longitude; //Get longitude
html5TimeStamp = position.timestamp; //Get timestamp
html5Accuracy = position.coords.accuracy; //Get accuracy in meters
return (html5Lat).toFixed(8) + ", " + (html5Lon).toFixed(8);
}
//Check value is present or not & call google api function
function initializeCurrent(latcurr, longcurr) {
currgeocoder = new google.maps.Geocoder();
console.log(latcurr + "-- ######## --" + longcurr);
if (latcurr != '' && longcurr != '') {
var myLatlng = new google.maps.LatLng(latcurr, longcurr);
return getCurrentAddress(myLatlng);
}
}
//Get current address
function getCurrentAddress(location) {
currgeocoder.geocode({
'location': location
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0]);
$("#address").html(results[0].formatted_address);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
});
</script>
I am trying to display map with current location using google map API using java script but unable to fetch the user's current location.I am explaining my code below.
window.onload = function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
alert("Geo Location is not supported on your current browser!");
}
function success(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var city = position.coords.locality;
var myLatlng = new google.maps.LatLng(lat, long);
var myOptions = {
center: myLatlng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title: "lat: " + lat + " long: " + long + "city:" + city
});
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({ content: "<b>User Address</b><br/> Latitude:" + lat + "<br /> Longitude:" + long + "<br /> City:"+city+"" });
infowindow.open(map, marker);
}
}
And also i am using the below script links.
<script type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&key=AIzaSyBIHSCiXA9Nfc6c40gSMMJ5ZaBHkcm1PoA&sensor=false"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
But finally it is giving me the output city name undefined.Please help me to resolve this issue.
After get the lat and lng from position.coords, you may want to use geocoder to the get the city name. Check the code below
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder
.geocode(
{
'latLng' : latlng
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var arrAddress = results;
console.log(results);
// iterate through address_component array
$
.each(
arrAddress,
function(i, address_component) {
if (address_component.types[0] == "locality") {
console.log("City: "
+ address_component.address_components[0].long_name);
itemLocality = address_component.address_components[0].long_name;
}
});
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
Although there may be a lot of examples found on google which contain coords.locality this property isn't documented somewhere(at least not in the Geolocation-API)
You'll need to run geocoding to get details like a city-name.
I have a function in my map controller to convert an address to a google.maps.latlng and I want to return this value, but my function doesn't return anything. I think thats because the values change inside another function, but I can't figure out how to solve this.
addressToLatLng: function(address) {
var geocoder = new google.maps.Geocoder(), lat, lng, latlng;
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
latlng = new google.maps.LatLng(lat, lng);
console.log(latlng); // will give me the object in the log
}
});
return latlng; // nothing happens
},
That's because the geocode call is asynchronous, so you are trying to return the value before it exists.
You can use a callback for the caller to get the value when it arrives:
addressToLatLng: function(address, callback) {
var geocoder = new google.maps.Geocoder(), lat, lng, latlng;
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
latlng = new google.maps.LatLng(lat, lng);
callback(latlng);
}
});
},
Usage:
yourController.addressToLatLng(address, function(latlng){
console.log(latlng);
});
I'm trying to remove a marker on my map based on it's address but it's not working for some reason. It must be something obvious that i'm not seeing. It's not going into the if(m==locationsall[i][0]) in the deleteMarker method even though i've ensured that m and locationsall[i][0] are identical.
//alert(tmp);
//alert(locationsall[0][0]);
Adding to map code:
$('#map').show();
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("address").value +", " + document.getElementById("city").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
locationsall[counter] = new Array();
locationsall[counter][0] = address;
locationsall[counter][1] = lat;
locationsall[counter][2] = lng;
var mapOptions = {
zoom: 13,
center: new google.maps.LatLng(lat, lng),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var i;
for (i = 0; i < locationsall.length; i++) {
locationsall[i][3] = marker = new google.maps.Marker({
position: new google.maps.LatLng(locationsall[i][1], locationsall[i][2]),
map: map
});
//markersArray.push(marker);
}
counter++;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Code that retrieves the address from a textbox and formats it to '1 main street, city'
var tmp = locations.splice(locations.indexOf(location), 1);
deleteMarker(tmp);
Delete marker code:
function deleteMarker(m){
for (i = 0; i < locationsall.length; i++) {
if(m==locationsall[i][0]){
alert(locationsall[i][0]);
alert(locationsall[i][3]);
locationsall[i][3].setMap(null);
}
}
}
Turns out I had an extra space when I compared m and locationsall[i][0];
The code works perfectly now.
I'm trying to implement google maps and the problem I am having is that when I call the function getLatLng, it is returning an undefined value and I can't figure out why.
initialize();
var map;
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var address = "Rochester, MN";
var myLatLng = getLatLng(address);
console.log("myLatLng = "+myLatLng);
}
function getLatLng(address) {
var codedAddress;
geocoder.geocode({'address': address}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
codedAddress = results[0].geometry.location;
console.log("codedAddress 1 = "+codedAddress);
} else {
alert("There was a problem with the map");
}
console.log("codedAddress 2 = "+codedAddress);
});
console.log("codedAddress 3 = "+codedAddress);
return codedAddress;
}
In the firebug console, here is the output that I get in this exact order:
codedAddress 3 = undefined
myLatLng = undefined
codedAddress 1 = (44.0216306, -92.46989919999999)
codedAddress 2 = (44.0216306, -92.46989919999999)
Why is codedAddress 3 and myLatLng showing up first in the console?
geocode is asynchronous (i.e. it sends a request to Google's servers), so you need to pass a callback function to getLatLng, rather than having it return immediately:
function getLatLng(address, callback) {
var codedAddress;
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
codedAddress = results[0].geometry.location;
console.log("codedAddress 1 = "+codedAddress);
} else {
alert("There was a problem with the map");
}
console.log("codedAddress 2 = "+codedAddress);
callback(codedAddress);
});
}
Here's what I got to work via the Google Maps documentation:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var address = "Rochester, MN";
var latlng = codeAddress(address);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function codeAddress(address) {
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
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Here's a jsFiddle to see it in action. Obviously, you can update this to use jQuery if you need to.
You're missing a closing } for the initialize function.