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);
};
}
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 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({...});
I want to use google map but only at the country level i.e i want to show whole world map in single window and user should be able to select any country on clicking of the country , also i should be able to show some popups .I also want to get the value of country selected from JS. Please guide me on this. I did google on this but no complete info.
Combine these two examples:
Zoom to country
clickable world map
click to zoom to country
var map=null;
var geocoder = null;
var kmlLayer = null;
var infoWindow = new google.maps.InfoWindow(); // InfoWindow
function openIW(layerEvt) {
if (layerEvt.row) {
var content = layerEvt.row['admin'].value;
} else if (layerEvt.featureData) {
var content = layerEvt.featureData.name;
}
document.getElementById('info').innerHTML = "you clicked on:<br>"+content;
findAddress(content);
}
function initialize() {
geocoder = new google.maps.Geocoder();
var chicago = new google.maps.LatLng(36.4278,-15.9);
var myOptions = {
zoom: 2,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, "click", function() {
document.getElementById('info').innerHTML = "";
});
kmlLayer = new google.maps.KmlLayer('http://www.geocodezip.com/geoxml3_test/world_countries_kml.xml', {preserveViewport: true, suppressInfoWindows: true} );
kmlLayer.setMap(map);
google.maps.event.addListener(kmlLayer, 'click', openIW);
}
function findAddress(address) {
if ((address != '') && geocoder) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results && results[0] && results[0].geometry && results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
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.