hi i am using Bing map in my website and want lat long to pinpoint that location on Bing map. my question is in my website how can i get lat long of an area using pincode. Is there any api that i can use to query lat long with by giving area pin code. i want to do it in backend. using some ajax call to that particular web api and get back lat lang and saved it into database so that i can use that lat long to plot location on my bing map.
i am using bing map 7 where i need to put lat long value into a json object and pass it into Bing map.
function GetMap()
{
var mapOptions = {
credentials: "Your Bing Maps Key",
center: new Microsoft.Maps.Location(47.592, -122.332), // i want these value in my database
mapTypeId: Microsoft.Maps.MapTypeId.birdseye,
zoom: 17,
showScalebar: false
}
var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), mapOptions);
}
i can hard code it but in my application i have given client an option which is use to add new location so in back end i want it like when client add any new location it automatically save its lat long also.
thanks
Using pincodes for obtaining the lat, long values may not be the best solution, since pin codes though popular for more than a century are still not a standard round the world. for example in US pincodes (zip codes) are normally have 5 digits (i.e. 06160) and in my part of the world their are normally 6 digits or more..
Though you can use combination of street address, state, country and pin code to find out the nearly correct geo coordinates for almost every part of the world. See following script which calls google api for finding the Lat, Long value... Here by I donate this code to the community under GPL:-
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"> </script>
<script src="http://maps.google.com/maps?file=api&v=3&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"> </script>
<script type="text/javascript">
var geocoder, location1;
function initialize() {
geocoder = new GClientGeocoder();
}
function prepareQuery(){
var query='';
var a1 = document.getElementById('address1').value;
var a2 = document.getElementById('address2').value;
var a3 = document.getElementById('address3').value;
var cty = document.getElementById('city').value;
var stat = document.getElementById('state').value;
var cntry =document.getElementById('country').value;
var pin = document.getElementById('pincode').value;
if(a1 != null && a1!=''){
query = query + a1 + ",";
}
if(a2 != null && a2!=''){
query =query + a2 + ",";
}
if(a3 != null && a3!=''){
query = query + a3 + ",";
}
if(cty != null && cty!=''){
query = query + cty + ",";
}
if(stat != null && stat!=''){
query = query + stat + ",";
}
if(cntry != null && cntry!=''){
query = query + cntry + ",";
}
if(pin != null && pin!=''){
query = query + pin + ",";
}
// alert("Prepare Query Returns " +query);
return query;
}
function submitFunc(){
var location = prepareQuery();
geocoder.getLocations(location, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the address");
}
else
{
location1 = {latitude: response.Placemark[0].Point.coordinates[1], longitude: response.Placemark[0].Point.coordinates[0], Address : response.Placemark[0].address};
var items = [];
$.each(location1, function(key, value){
items.push('<li id="' + key + '">' + key +" : "+ value + '</li>');
});
// alert(items)
$("body").append("Results is :-");
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
}
});
}
</script>
and the html looks like....
Line 1 : <input type="text" id="address1" value="" placeholder="Enter first line of address."/> <br></br>
Line 2 :<input type="text" id="address2" value="" placeholder="Enter second line of address."/> <br></br>
Line 3 :<input type="text" id="address3" value="" placeholder="Enter third line of address."/> <br></br>
City : <input type="text" id="city" value="" placeholder="Enter city name."/> <br></br>
State : <input type="text" id="state" value="" placeholder="Enter state name."/> <br></br>
Country : <input type="text" id="country" value="" placeholder="Enter country name."/> <br></br>
Pin Code : <input type="text" id="pincode" value="" placeholder="Enter pincode value."/> <br></br>
<input type="button" name="submitBtn" value="submit" onclick='submitFunc();'/> <br></br>
<h3> <strong> Your Results Will be displayed Here . . . .</strong> </h3>
Geonames is a good service for all kind of location stuff, take a look at the list of the services they provide:
http://www.geonames.org/export/ws-overview.html
Could you use the one to look up postal codes? api.geonames.org/postalCodeLookupJSON?postalcode=6600&country=AT&username=demo
Related
Like the title suggests, I'm trying to allow the user to manually change the javascript coordinate variables in order to get a list of results based off of the coordinates that they entered. I managed to save latitude and longitude into variables which can be plugged into the api key. However I just can't figure out how to adjust those variables from html so that the user can adjust the coords without having to go into the javascript file. I'll attach the relevant code below.
Thanks!
Html
<input id="lat" placeholder="Enter the latitude of your desired hiking location">
<input id="long" placeholder="Enter the longitude of your desired hiking location">
<button value="send" id="submit" onclick="latFunc(); longFunc() ">Search</button>
Javascript
let latitude = "40.2398"
let longitude = "-76.9200"
function latFunc() {
let latitude = document.getElementById("lat").value;
console.log(latitude);
}
function longFunc() {
let longitude = document.getElementById("long").value;
console.log(longitude);
}
latFunc();
longFunc();
$.getJSON("https://www.hikingproject.com/data/get-trails?lat=" + latitude + "&lon=" + longitude + "&maxDistance=10&key=*****************", function (data) {
Have your functions return the value, rather than assigning a variable.
function latFunc() {
return document.getElementById("lat").value;
}
function longFunc() {
return document.getElementById("long").value;
}
When calling the getJSON, use the values by returning value from lat/long inputs. Assuming this code gets executed on a click handler.
$.getJSON("https://www.hikingproject.com/data/get-trails?lat=" + latFunc() + "&lon=" + longFunc() + "&maxDistance=10&key=*****************", function (data) ...
When you initialize, assign your lat/long. You could also encapsulate this into methods.
document.getElementById("lat").value = "40.6";
document.getElementById("long").value = "-75";
Seems like you use jQuery here, here's a complete func handler for click with console to show you the requested URL value.
$("#submit").click(function(e) {
e.preventDefault();
const latitude = $("#lat").val() ;
const longitude =$("#long").val();
console.log(latitude);
console.log(longitude);
var url = "https://www.hikingproject.com/data/get-trails?lat=" + latitude + "&lon=" + longitude + "&maxDistance=10&key=*****************";
console.log(url);
$.getJSON(url, function (data) {
console.log(data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="lat" value="40.2398" placeholder="Enter the latitude of your desired hiking location">
<input id="long" value="-76.9200" placeholder="Enter the longitude of your desired hiking location">
<button value="send" id="submit">Search</button>
But in case you want to stick with what you have done so far:
function callApi() {
const latitude = document.getElementById("lat").value;
let longitude = document.getElementById("long").value;
console.log("latitude: " + latitude);
console.log("longitude: " + longitude);
var url = "https://www.hikingproject.com/data/get-trails?lat=" + latitude + "&lon=" + longitude + "&maxDistance=10&key=*****************";
console.log(url);
$.getJSON(url, function (data) {
console.log(data);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="lat" placeholder="Enter the latitude of your desired hiking location">
<input id="long" placeholder="Enter the longitude of your desired hiking location">
<button value="send" id="submit" onclick="callApi() ">Search</button>
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
There's a form on my webpage which is supposed to get the address of the user in a formfield.
When the user clicks allow on the location prompt my purpose is to get the address of the user in an input box in the form.
The prompt comes but this code is unable to fetch the address of the user.
I am looking for something like this
Here's my code
HTML
<form id="contact" action="" method="post" align="center">
<fieldset>
<input placeholder="Your Address" id="address" type="text" tabindex="1" required autofocus>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
Javascript
<script src="https://code.jquery.com/jquery-1.10.1.js"></script>
<script>
$(document).ready(function () {
var currgeocoder;
//Set geo location 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
function initializeCurrent(latcurr, longcurr) {
currgeocoder = new google.maps.Geocoder();
console.log(latcurr + "-- ######## --" + longcurr);
if (latcurr != '' && longcurr != '') {
//call google api function
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);
}
});
}
});
Try this-
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script type="text/javascript">
$(document).ready(function(){
function getGeoLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
document.getElementById("address").value = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var lang = position.coords.longitude;
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lang + "&sensor=true";
$.getJSON(url, function (data) {
var address = data.results[0].formatted_address;
document.getElementById("address").value = address;
});
}
});
</script>
The url http://maps.googleapis.com/maps/api/geocode/json?latlng=22.3545947,91.8128751&sensor=true returns address information in JSON format. You want the "formatted_address" of 0 index inside the "result" index of the JSON.
See the JSON file for more information.
In order to start using Google Maps API, you need to include the Google Maps JS file into your script.
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
You need to replace YOUR_API_KEY with your own key. You need to generate one for your application.
Get API Key
There is another issue in your code at this line.
$("#address").html(results[0].formatted_address);
The element with id="address" is an input field, so the .html() function is not available on it. You need to use the .val() function. So you can replace that line with the one below.
$("#address").val(results[0].formatted_address);
This should get your code working.
The reason your textfield is not being populated with the address is because of this line in your code:
In "getCurrentAddress" function:
$("#address").html(results[0].formatted_address);
The problem, in this line is that you want to set an input "textfield". In this case you cannot do .html()
You can fix this by changing it to:
$("#address").val(results[0].formatted_address);
Take a look at the following fiddle:
https://jsfiddle.net/ezr6z7so/
good evening all,
I want to know how to display the import data from page 1 to the view in page 2 calling the function GetRoute() from input .
this is my code :
Html page 1 :
<div> Add Destination</div>
<div>
<input id="travelto" type="text" name="name" value="Oving, UK" />
<input type="button" value="Add" onclick="PushDestination()" />
Tagmere, UK.
Bosham, UK
</div>
<div id="destinations"></div><br />
Source : <input id="travelfrom" type="text" name="name" value="Chichester, UK" /> <br /> <br />
<input type="button" value="Calculate" onclick="GetRoute()" />
html page2
the result will be displayed here in a table in the second page:
<div id="dvDistance">
<table id="tblResults" border="1" cellpadding="10">
<tr>
<th> Start </th>
<th> End </th>
<th> Distance </th>
<th> Duration </th>
</tr>
</table>
</div>
my function from javascript :
function GetRoute() {
directionsDisplay.setMap(map);
source = document.getElementById("travelfrom").value;
destination = document.getElementById("travelto").value;
var waypoints = [];
for (var i = 0; i < locations.length; i++) {
var address = locations[i];
if (address !== "") {
waypoints.push({
location: address,
stopover: true
});
}
}
var request = {
origin: source,
destination: waypoints[0].location,
waypoints: waypoints, //an array of waypoints
optimizeWaypoints: true, //set to true if you want google to determine the shortest route or false to use the order specified.
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var dvDistance = document.getElementById("dvDistance");
var distance = 0;
var minute = 0.00;
response.routes[0].legs.forEach(function (item, index) {
if (index < response.routes[0].legs.length - 1) {
distance = distance + parseInt(item.distance.text);
minute = parseFloat(minute) + parseFloat(item.duration.value / 60);
tbl = document.getElementById("tblResults");
var row = tbl.insertRow(1);
var cell = row.insertCell(0);
cell.innerText = source;
var cell = row.insertCell(1);
cell.innerText = item.end_address;
var cell = row.insertCell(2);
cell.innerText = distance;
var cell = row.insertCell(3);
cell.innerText = minute.toFixed(2) + " min";
}
});
directionsDisplay.setDirections(response);
}
else {
}
})
};
I have to display the result for it to be displayed in the second page, taking the data from the first page .
thnaks,
You can use HTML5 session o local storage:
sessionStorage.getItem('label')
sessionStorage.setItem('label', 'value')
or
localStorage.getItem('label')
localStorage.setItem('label', 'value')
depending on how long you want this results to be stored.
You can use the query string or the hash. Using the hash, you can then remove the hash from the url without refreshing the page. Also, you can use history.replaceState to remove the query string from the url without refreshing.
Here's an example:
http://id0t.x10.mx/StackOverflow/demo2a.html
Use it to get the source.
EDIT:
PAGE 1
<textarea onchange="sendres(myFunc(this.value),'/StackOverflow/demo2b.html');" placeholder="type in me and press enter (or click out of me) to submit!"></textarea>
<script>
function sendres(callback,url){
window.location.href=url+"?"+encodeURIComponent(callback);
}
function myFunc(text){
return text;
}
</script>
PAGE 2
<script>
window.onload=function(){
if((window.location.search.length==0)||(window.location.search.length==1)){
//no query string
document.getElementById("msg").style.display="none";
return;
}else{
res = decodeURIComponent(window.location.search.substr(1));
var url = window.location.origin+window.location.pathname;
history.replaceState({urlPath:url},"",url);
}
alert(res);
}
</script>
<span id="msg">Now, look at the URL. See how it has no query string?<br><button onclick="document.body.parentElement.innerHTML=atob();">Source</button></span>
<button onclick="window.location='/StackOverflow/demo2a.html';">to part 1</button>
we can use a Cookies for store data in it and we can use the data stored with request cookie .
I have got the current location with complete address and shown this in a <span> by ID. But i want to show this address in input type text also. My current code is
<script type="text/javascript">
var positionlatitude;
var positionlongitude;
var address;
google.maps.event.addDomListener(window, 'load', function () {
var places = new google.maps.places.Autocomplete(document.getElementById('location_#item.Name'));
google.maps.event.addListener(places, 'place_changed', function () {
var place = places.getPlace();
address = place.formatted_address;
positionlatitude = place.geometry.location.lat();
positionlongitude = place.geometry.location.lng();
});
});
navigator.geolocation.getCurrentPosition(success);
function success(position) {
var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
$.getJSON(GEOCODING).done(function (location) {
$('span[id^="address"]').html(location.results[0].formatted_address);
})
}
</script>
<label for="location">Your Location: </label><br />
<span id="address" class="input-form" ></span>
<input type="text" value="" name="address" id="geolocation"/>
Thanks To everyone If you consider this question.
now i got the answer.
document.getElementById("geolocation").value = location.results[0].formatted_address;
<input type="hidden" value="" name="address" id="geolocation"/>
This will set the address in input type hidden
I am working on an app related to addresses.
I tested my function with hardcoded address like this:
var address = "India Gate , Rajpath, New Delhi, Delhi";
It is working fine.
But now when I am using that function to get adderss from user through a form and using address=form.address.value. Then alert(address) is showing right address (string). But function couldn't work on it (for same address as hardcoded).
Basically I'm using Google Maps API. So is there anyhting special about form.name.value that I should know?
geocoder = new google.maps.Geocoder();
var address = form.address.value;
alert(address);
//var address = "India Gate , Rajpath, New Delhi, Delhi";
geocoder.geocode({
'address': address
}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
alert("hi");
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
addpin(latitude, longitude);
}
});
<form>
Your Name: <input type="text" name="name"/><br/>
Your Email:<input type="text" name="email"/><br/>
Company name:<input type="text" name="company"/><br/>
Street address:<input type="text" name="address"/><br/>
<input type="submit" value="submit" onclick="getlatlong(this.form)">
</form>
form.name reflects to the name attribute of the form element
<form name="form1" />
console.assert(form.name == "form1");
You could use form.elements.name which will be that you want. But in this case, you cannot reach the length named element, because that's the form.elements collection's length.