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.
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>
<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.
I am sending the google.geocoder several addresses, but the values in the results[0].geometry.location are all the same. I believe I have accounted for the asynchronous nature of the call using a call back. When I add alerts to see the values returned, the addresses passed in the geocoder.geocode( { 'address': addr }... are all correct, the status returned is "ok", but the lat/long are the same for every call. I am not very well versed in JavaScript, and am new to the .net environment, so any help would be greatly appreciated.
This code worked perfectly from 4/1/2012 until some time near December or early 2013. Has something changed with the Google API? I have looked at google's website but cannot find anything.
Here is my initial call:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var directionsDisplay;
var directionsRenderer;
var startPoint;
var endPoint;
function initialize()
{
geocoder = new google.maps.Geocoder();
codeAddress();
var myOptions =
{
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
setMarkers(map);
google.maps.event.addListener(map, 'click', function(event) {
dirMarker(event.latLng);
startPoint = event.latLng;
});
}
function codeAddress()
{
var address = document.getElementById("<%=hCVT.ClientID%>").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("Status: " + status + "res from CODE ADDRESS -- " + results[0].geometry.location); //TO REMOVE
map.setCenter(results[0].geometry.location);
} else {
alert("Geocode of CVT was not successful for the following reason: " + status);
}
});
}
The function to set the markers and info window information (I have removed some of the code that seemed irrelevant to the question)
function setMarkers(map)
{
// Add markers to the map
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
var places = new Array([,,,,]);
var xx = String;
xx = document.getElementById("<%=addys.ClientID%>").value;
var placeholder = xx.split(",");
var latlng;
var i = 0;
for(var y = 0; y < (placeholder.length / 5 - 1); i=i+5)
{
places[y, 0] = placeholder[i];
places[y, 1] = placeholder[i+1]; //Unit Status
places[y, 2] = placeholder[i+2]; // Long - not used
places[y, 3] = placeholder[i+3]; // Zindex
places[y, 4] = placeholder[i+4]; // HTML for information window
addr = places[y,0];
ustat = places[y,1];
zind = places[y,3];
iwdata = places[y,4];
getLatLong(addr, iwdata, ustat, zind, function(latlng, addr, iwdata, ustat, zind) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
html: iwdata,
icon: pinImage,
shadow: pinShadow,
shape: shape,
title: addr,
zIndex: parseInt(places[y,3])
});
var infowindow = new google.maps.InfoWindow({
content: iwdata});
});
y = y + 1;
}
}
The function where I believe the problem lies follows. Since there were several addresses being sent to google, I added a built in timeout so as to not exceed the limitations. Again, this all worked for about 8 months and has suddenly stopped. Where several markers used to show on the map, now there is one marker which is seeming over written because the lat/lng return is the same as the initial call in the codeAddress() function. In an effort to find a solution I have been adding alerts to show me the return values. I was getting confused with the bugzilla values as they would take me over to the google javascript which was completely over my head.
function getLatLong(addr, iwdata, ustat, zind, callback){
geocoder.geocode( { 'address': addr}, function(results, status){
if (status == google.maps.GeocoderStatus.OK){
callback(results[0].geometry.location, addr, iwdata, ustat, zind);
} else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
window.setTimeout(function() {self.getLatLong(addr, iwdata, ustat, zind, callback);
},500);
} else {
alert("Address Geocode failure: " + addr + " ==== " + status + "Y value: " + zind + " res ---" + res);
}
});
}
Can anyone help me with this?
Well, after some long hours of staring at this code trying to figure it out, I finally stumbled on something using smartly placed alerts. Apparently the addr variable contained "'" and the geocoder was not able to provide lat/lng data as a result. Adjusted this line:
addr = places[y,0].replace(/'/g, "");
All works now.
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 sure this is really simple but I haven't had much luck figuring out what's wrong. I'm creating an empty array (locations), filling it with location objects in the getPartnerLocations function and then trying to plot the locations on the map with the drop function. The problem I'm having is that inside the drop function the locations array which has stuff in it is returning a length of zero so the loop in the isn't working. Any tips or ideas about what's going on here would be greatly appreciated.
var markers = [];
var locations = [];
var iterator = 0;
var map;
var geocoder;
var newYork = new google.maps.LatLng(40.7143528, -74.0059731);
function initialize() {
var mapOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: newYork
};
map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
}
function getPartnerLocations() {
geocoder = new google.maps.Geocoder();
$('.partner').each(function(index){
var street = $('.partner-streetaddress',this).text();
var city = $('.partner-city',this).text();
var state = $('.partner-state',this).text();
var country = $('.partner-country',this).text();
var address = street + ', ' + city + ', ' + state + ', ' + country;
geocoder.geocode( { 'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
locations.push( results[0].geometry.location );
console.log(locations[index]);
}
else
{
console.log('failed to geocode address: ' + address);
}
});
});
initialize();
drop();
}
function addMarker() {
console.log('add marker function');
markers.push(new google.maps.Marker({
position: locations[iterator],
map: map,
draggable: false,
animation: google.maps.Animation.DROP
}));
iterator++;
}
function drop()
{
console.log(locations.length);
for (var i = 0; i < locations.length; i++) {
setTimeout(function() {
addMarker();
}, i * 200);
}
}
getPartnerLocations();
geocode is an asynchronous function.
The callback doesn't execute until some time after you call drop.
Therefore, when you call drop, the array is still empty.
You need to call initialize and drop after the last AJAX call replies, in the geocode callback.