How to get current location name from longitude and latitude? - javascript

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>

Related

Laravel form request with geocoder

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);
}
});
}

Asp.net using javascript, I have taken from Google maps how to save data to the database

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDX1D37MapC2HfewVE0T3MXcUT4bstvHq8&callback=initMap" type="text/javascript"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction() {
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
var mapOptions = {
zoom: 15,
center: latlng,
mapTypeControl: true,
navigationControlOptions:
{
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(
document.getElementById("mapContainer"), mapOptions
);
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
alert(results[0].formatted_address)
//find country name
for (var i = 0; i < results[0].address_components.length; i++) {
for (var b = 0; b < results[0].address_components[i].types.length; b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city = results[0].address_components[i];
break;
}
}
}
// city data
alert(city.short_name + " " + city.long_name)
}
else {
alert("No results found");
}
}
else {
alert("Geocoder failed due to: " + status);
}
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Your Location"
});
});
}
</script>
2-3 hours, I'm looking on the internet and I try, but I did not get results. I'm trying another code block, latitude and longitude can save the database. This is not just what I wanted, and I want to save the city formatted address.
I opened issue in another forum, not responding.
I need a lot of help. Code could bring up here. This issue of homework project.

Get from a Draggrable Marker new street and town

I've a google maps with a draggrabble marker that in infowindow show the street and town
NOw I use this code to get new lng e lat in a form when marker is dragged
var geocoder = new google.maps.Geocoder;
function geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addListener(marker, 'dragend', function (event) {
document.getElementById("lat").value = this.getPosition().lat();
document.getElementById("lng").value = this.getPosition().lng();
document.getElementById("latlng").value = this.getPosition().lat()+','+this.getPosition().lng();
geocodeLatLng(geocoder, map, infowindow);
});
In the input lng, lat, latlng all is ok so the value change moving the marker, but I can determine the value of 2 other input that are city and street
I'm looking for something like
document.getElementById("address").value = this.address;
document.getElementById("city").value = this.city;
The result components contain element organized in this way
results[0].components
filtering n.th result[0].components[n].types by the
route matches long or short name of a route.
locality matches against both locality and sublocality types.
administrative_area matches all the administrative_area levels (administrative_area_level_3.political = town/city , administrative_area_level_2.political = province/county, administrative_area_level_1.political = country)
postal_code matches postal_code and postal_code_prefix.
country matches a country name or a two letter ISO 3166-1 country code.
you can get what you need in
result[0].components[n].long_name
if you want only locality you should iterate this way
for (var i=0; i < results[0].address_components.length; i++ ) {
if (results[0].address_components[i].types == 'locality,political') {
window.alert(results[0].address_components[i].long_name);
};
}

Failed to get user's current position using google map API

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.

Mark multiple locations in Google Map

I am using Google map api v3 to plot markers of location array. My script is
function OnSuccess(response) {
var markers = response.d.split('^^');
var latlng = new google.maps.LatLng(51.474634, -0.195791);
var mapOptions1 = {
zoom: 14,
center: latlng
}
var geocoder = new google.maps.Geocoder();
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions1);
for (i = 0; i < markers.length; i++) {
var data = markers[i];
geocoder.geocode({ 'address': data }, 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: data
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
(function (marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data);
infoWindow.open(map, marker);
});
})(marker, data);
}
where markers variable is bringing proper data, my test data is array of 5 elements
The Game Larder, 24 The Parade, Claygate, Surrey,KT10 0NU
24 The Parade, Claygate, Esher, Surrey KT10 0NU
Card Collection, 14 The Parade, Claygate, ESHER, KT10 0NU
16A The Parade, Claygate, ESHER, KT10 0NU
and same is coming into array markers however it is plotting only two markers. What could be wrong here
Solution
I was entering locations which are very close to each other e.g 1 and 2 point which gives same latlong hence mark as one place. I found latlong here. Thanks for answers btw :)
In page.aspx. insert tag <div id="map-canvas" ></div>
view source page.aspx and insert script into it>
var lis_marker = new Array();
for (i = 0; i < markers.length; i++) {
var data = markers[i];
geocoder.geocode({ 'address': data }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
lis_marker[i] = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: data
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
there are difference with your code:
1: var lis_marker = new Array();
2: lis_marker[i] = new google.maps.Marker({...});

Categories