Convert geocode results into php variables to post to mysql database - javascript

I have used the tutorial here http://tech.cibul.net/geocode-with-google-maps-api-v3/ to create a page with map and draggable marker to display address and lat/long.
Demo - http://www.calcunation.com/testgeo.php
How do I captured those results and put them into a php variable so I can insert into a mysql database?
I'm relatively new to Java, and fairly comfortable with PHP.

AJAX would be the cleanest from a user perspective. I'd use jquery $.post to do it http://api.jquery.com/jQuery.post/.

Are you trying to split out the address components?
Like street, city, state, zip....
If so...you'll want to look at the geocoded result, and parse through the array of address types that it returns.
Here is some quick sample code you can use...
//Startup a new geocode instance
var geocoder = new google.maps.Geocoder();
//event.latLng is a latLng object passed into the geocode function to get
your addy results
geocoder.geocode({'location': event.latLng}, function(results, status) {
//Show the results here
console.log(results);
if (status == google.maps.GeocoderStatus.OK) {
var addressResults = results[0].address_components;
var address1 = "";
var address2 = "";
var city = "";
var state = "";
var zipCode = "";
for(var i = 0; i < addressResults.length; i++){
for(var j = 0; j < addressResults[i].types.length; j++){
if(addressResults[i].types[j] == 'street_number'){
address1 = addressResults[i].long_name;
break;
}
if(addressResults[i].types[j] == 'route'){
address1 += " " + addressResults[i].long_name;
break;
}
if(addressResults[i].types[j] == 'subpremise'){
address2 = addressResults[i].long_name;
break;
}
if(addressResults[i].types[j] == 'locality'){
city = addressResults[i].long_name;
break;
}
if(addressResults[i].types[j] == 'administrative_area_level_1'){
state = addressResults[i].short_name;
break;
}
if(addressResults[i].types[j] == 'postal_code'){
zipCode = addressResults[i].long_name;
break;
}
}
}
//Do ajax post to your form here with the data you just parsed out
}
});

Related

How to pass javascript alert message value to label in asp.net

I had implemented geolocation , wherein browser gets location of user.
In this code i'm getting geolocation of user through browser ,but it display location using javascript alert message.
I just want to pass alert message value to label or hiddenfield in ASP.Net & doesn't want to run alert message
My javascript code as follows.
<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);
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)
document.getElementById('<%=Label1.ClientID %>').innerHTML = city;
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
If you want to store the value in a hidden field replace
alert(results[0].formatted_address)
with
//hdnField is the ID of your asp:HiddenField object
var hiddenField = document.getElementById("<%= hdnField.ClientID %>")
hiddenField.value = results[0].formatted_address;

How to remove markers dynamically with Google Maps API?

I'm writing a program that take in an address, state, or zip code. Queries our database take the results and push them to maps and markers with Google Maps API.
Here is the function to add a marker to the page:
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 is how I'm pushing the addresses to the function:
function get_matches()
{
var info_ = document.getElementById('address').value;
$.ajax({ url: 'find_store.php',
data: {info: info_},
type: 'get',
success: function(output) {
var html = output;
$('#dress').html(html);
var num =$('#row_c').html();
var counter = 0;
while(counter < num)
{
var addr = $('.addre#'+ counter).html();
codeAddress(addr);
counter++;
}
}
});
}
Basically with this function according to their input it will return the correct store outputs them into a div and unordered list. I'm passing the number of rows to the inner HTML of a hidden div "#row_c" then I run through a loop which grabs all the addresses from every div outputted to the screen.
Here is an example of how I get the information for when a user inputs the state abbreviation.
else if($type == 2)
{
$row_count = 0;
$z_query = "select * from store_table where state like '%$accept%' and address like '%$accept%' limit 10";
$result = mysql_query($z_query);
$num_rows = mysql_num_rows($result);
if($num_rows == 0)
{
echo"<script>alert(\"Your State look-up was unsuccessful, please try again\")</script>";
}
$width = ($num_rows * 300)."px";
if($num_rows > 0)
{
echo"<div id = 'state_container' style = \" margin:none; height:200px; backround-color:hsl(0,0%,95%); position:relative; padding:0px; overflow-x:hidden; overflow-x:scroll; overflow-y:none;\">";
echo"<ul style = 'list-style-type:none; margin-top:0px; margin-left:0px; padding-left:0px; width:$width;'>";
while($row = mysql_fetch_assoc($result))
{
$state = "".$row['state']."";
$store = "".$row['store_name']."";
$phone = "".$row['phone']."";
$addr = "".$row['address']."";
$website = "".$row['website']."";
$state = preg_replace('/\s+/', '', $state);
$phone = preg_replace('/\s+/', '', $phone);
$website = preg_replace('/\s+/', '', $website);
$state = stripslashes($state);
$store = stripslashes($store);
$phone = stripslashes($phone);
$addr = stripslashes($addr);
$website = stripslashes($website);
echo"<li style = 'float:left; margin:none; margin-left:5px; margin-right:10px;'>";
echo"<br/><b>$store</b>";
echo"<br />$phone";
echo"<br /><div class = 'addre' id = '$row_count' style = 'margin:0px; padding:0px;'>$addr</div>";
echo"<br /><a href='$website' style = 'color:#000000; text-decoration:none;'>$website</a>";
echo"</li>";
$row_count++;
}
echo"<script>$('#row_c').html($row_count)</script>";
echo"</ul>";
echo"</div>";
}
}
How can I delete previous markers? For example if a user goes and searches 'CA' that's great everything works fine and dandy. But if the same user want to search anything else - let's say a specific zip code in California - it does the search but all the previous markers are still there, making their second search pointless.
First you need to store all your markers in an array.
var hotSpotMapMarkers = [];
Then as you create your markers, you store them in the array at the same time you assign them to the map.
hotSpotMapMarkers.push(<your marker object>);
Then, the next time you refresh your map, remove all the markers first. Something like this:
// Clear all markers currently on the map
for (var i = 0; i < hotSpotMapMarkers.length; i++)
hotSpotMapMarkers[i].setMap(null);
This code is from an app I've written that does exactly this. By the way, there are plenty of examples, which can be found by using Google, that shows how to do this.
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}

Google geocoder - Asynchronous request return "undefined" value

I have this function that should return the country starting from the latitude and longitude and assign it to a global variable declare outside the function. I know that the a in Ajax stand for asynchronous and I have read every single answer on stackoverflow but I can't fix it.
function getLatLongDetail(myLatlng) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': myLatlng },
function (results, status) {
var country = "";
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
for (var i = 0; i < results[0].address_components.length; i++) {
var addr = results[0].address_components[i];
// check if this entry in address_components has a type of country
if (addr.types[0] == 'country')
country = addr.long_name;
}
}
return country; // this doesn't work
}
}
});
}
var Country = getLatLongDetail(myLatlng);
alert(Country);// undefined
I know there are hundreds of questions about callback function but none of them worked for me.
Finally I made it! Here the code:
function getLatLongDetail(myLatlng, fn) {
var geocoder = new google.maps.Geocoder();
var country = "";
var city = "";
var address = "";
var zip = "";
var state = "";
geocoder.geocode({ 'latLng': myLatlng },
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
for (var i = 0; i < results[0].address_components.length; i++) {
var addr = results[0].address_components[i];
// check if this entry in address_components has a type of country
if (addr.types[0] == 'country')
country = addr.long_name;
else if (addr.types[0] == ['locality']) // City
city = addr.long_name;
else if (addr.types[0] == 'street_address') // address 1
address = address + addr.long_name;
else if (addr.types[0] == 'establishment')
address = address + addr.long_name;
else if (addr.types[0] == 'route') // address 2
address = address + addr.long_name;
else if (addr.types[0] == 'postal_code') // Zip
zip = addr.short_name;
else if (addr.types[0] == ['administrative_area_level_1']) // State
state = addr.long_name;
}
}
fn(country,city, address, zip, state);
}
});
}
var mCountry; //global variable to store the country
vat mCity; //global variable to store the city
getLatLongDetail(event.latLng, function(country,city, address, zip, state){
mCountry = country; // now mCountry store the value from getLatLongDetail so I can save it in the database
mCity = city;
alert(address + zip + state);
});

how do i convert Lat and Long to uk postcode with Javascript

I'm trying to make use of HTML5 geolocation for a project I'm working on.
It seems pretty straighforward to get the Lat and Long of where a user is, via geolocation.
Problem is, I need to convert this to a UK postcode, and am strugging as I'm trying to learn javascript.
The code I have working is:
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by this browser");
}
function displayPosition(position) {
alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
var Lat = position.coords.latitude;
var Long = position.coords.longitude;
var inputField = document.getElementById("addressInput");
inputField.value = Lat + Long;
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
I've found this site, whihc does exactly the kind of thing I want to achieve:
http://www.latlong.net/Show-Latitude-Longitude.html
Can anyone give me some tips on how to get this working?
Any advice would be great
thanks in advance
=========================
Amended code:
//var long = '50.**************', lat = '0.**************'
var Lat='';
var Long='';
var coordsObj = {coords:{latitude:Lat, longitude:Long}};
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by this browser");
}
function displayPosition(position) {
console.log(position, position.coords)
console.log("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
var Lat = position.coords.latitude;
alert(Lat);
var Long = position.coords.longitude;
alert(Long);
var inputField = document.getElementById("addressInput");
inputField.value = Lat + Long;
return [Lat, Long];
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
function reverseGeoLookup(lon, lat) {
var req = new XMLHttpRequest()
req.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=true", true)
req.onreadystatechange = function() {
if(req.readyState == 4) {
var result = JSON.parse(req.response).results
for(var i = 0, length = result.length; i < length; i++) {
for(var j = 0; j < result[i].address_components.length; j++) {
var component = result[i].address_components[j]
if(~component.types.indexOf("postal_code")) {
var out = document.getElementById('output')
out.innerHTML += component.long_name
}
}
}
}
}
req.send()
}
var latlng = displayPosition(coordsObj)
reverseGeoLookup.apply(this, latlng)
There's now a free UK government alternative to the other options listed here. Go to http://postcodes.io/ to see the details of the API and examples. It also supports reverse lookups which is what you're after
You could use the Google Maps reverse geocoding API. This allows you to map a lat, long pair to a set of addresses. For example:
function reverseGeoLookup(lon, lat) {
//make a ajax request -- in prod just use whatever libraryyou have to provide this
//probably jquery's $.get
var req = new XMLHttpRequest()
//put the longitude and latitude into the API query
req.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=true", true)
//this is just the result callback -- it's the function arg to $.get, essentially
req.onreadystatechange = function() {
if(req.readyState == 4) {
//again jquery will parse for you, but we want the results field
var result = JSON.parse(req.response).results
//the maps API returns a list of increasingly general results
//i.e. street, suburb, town, city, region, country
for(var i = 0, length = result.length; i < length; i++) {
//each result has an address with multiple parts (it's all in the reference)
for(var j = 0; j < result[i].address_components.length; j++) {
var component = result[i].address_components[j]
//if the address component has postal code then write it out
if(~component.types.indexOf("postal_code")) {
var out = document.getElementById('output')
out.innerHTML += component.long_name
}
}
}
}
}
//dispatch the XHR... just use jquery
req.send()
}
I put this example into a js fiddle too, here.
Hope this helps.
I've made some changes to kieran's fiddle to more to help fully answer the question of getting a UK postcode from an html5 geolocation.
var x=document.getElementById("output");
getLocation();
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.watchPosition(reverseGeoLookup);
}
else
{
x.innerHTML="Geolocation is not supported by this browser.";
}
}
function reverseGeoLookup(position) {
console.log(position);
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var req = new XMLHttpRequest()
req.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=true", true)
req.onreadystatechange = function() {
if(req.readyState == 4) {
var result = JSON.parse(req.response).results
for(var i = 0, length = result.length; i < length; i++) {
for(var j = 0; j < result[i].address_components.length; j++) {
var component = result[i].address_components[j]
//console.log(component.long_name);
if(~component.types.indexOf("postal_code")) {
var out = document.getElementById('output');
out.innerHTML = 'Approximate Post Code for your location is ' + component.long_name;
return false;
}
}
}
}
}
req.send()
}
http://jsfiddle.net/ef72Q/28/

User shared GEOlocation does not work with google places

I don't know how to search for this in SO, so I'm asking a new question. What could cause or what is the concrete problem of my code: HTML generated by Javascript (createElement() and appendChild) is not being shown in Opera and Firefox, but it works in Chromium.
The HTML generating code:
function typesOfPlaces(map, bounds) {
var allowedTypes = [
"amusement_park",
"aquarium",
"art_gallery",
"cemetery",
"church",
"city_hall",
"hindu_temple",
"mosque",
"museum",
"night_club",
"park",
"place_of_worship",
"rv_park",
"spa",
"synagogue",
"travel_agency",
"zoo"
];
var typesToDisplay = new Array();
var request = {
bounds: bounds,
types: allowedTypes
};
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, function(results, status) {
if(status == google.maps.places.PlacesServiceStatus.OK) {
for(var i = 0; i < results.length; i++) {
for(var j = 0; j < results[i].types.length; j++) {
for(var k = 0; k < allowedTypes.length; k++) {
if(results[i].types[j] == allowedTypes[k]) {
var allowed = true;
for(var x = 0; x < typesToDisplay.length; x++) {
if(allowedTypes[k]==typesToDisplay[x]) {
allowed = false;
}
}
if(allowed) {
typesToDisplay.push(allowedTypes[k]);
}
}
}
}
}
var parent = document.getElementById("types");
for(var i = 0; i < typesToDisplay.length; i++) {
var typeBox = document.createElement("div");
var checkBox = document.createElement("input");
var checkID = randomString(10);
var label = document.createElement("label");
checkBox.setAttribute("type", "checkbox");
checkBox.setAttribute("id", checkID);
label.setAttribute("for", checkID);
label.innerHTML = typesToDisplay[i];
typeBox.appendChild(checkBox);
typeBox.appendChild(label);
parent.appendChild(typeBox);
}
}
});
}//END OF Function
UPDATE TO COMMENTS
The randomString is just SO'ed code for generating random string:
function randomString(L) {
var s= '';
var randomchar=function() {
var n= Math.floor(Math.random()*62);
if(n<10) return n; //1-10
if(n<36) return String.fromCharCode(n+55); //A-Z
return String.fromCharCode(n+61); //a-z
}
while(s.length< L) s+= randomchar();
return s;
}
div #types really exists, it look like this:
<html>
<head>
...
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MyKey&sensor=false&libraries=places&language=lt"></script>
</head>
<body>
<div>
<div>
<div id="types"></div>
</div>
</div>
</body>
</html>
You can see the import of google.maps.places.PlacesService by looking at the <head> section of the <script> tag, where you can see "&libraries=places".
SECOND UPDATE AFTER SOME TESTING
ok. I've figured out that if I deny location sharing in opera it works (it works in chromium because by default it does not even ask user if he is kind to share his geolocation with website)
The code for geolocation:
function initGeo()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
else
{
errorFunction();
}
}
so, the function that does not work is successFunction (which is being launched if user kindly shares his geolocation)
function successFunction(position)
{
var geocoder = new google.maps.Geocoder();
var abstract_location;
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
abstract_location = new google.maps.LatLngBounds(
results[0].geometry.viewport.getSouthWest(),
results[0].geometry.viewport.getNorthEast());
}
else
{
alert("NOT SUCCESS 1");
}
showGMap(latlng, abstract_location);
});
}
And the errorFunction, which successfully works on chromium by default and on Opera if you deny access to your geolocation:
function errorFunction(error)
{
var geocoder = new google.maps.Geocoder();
if(google.loader.ClientLocation)
{
var latlng = new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var abstract_location = new google.maps.LatLngBounds(
results[0].geometry.viewport.getSouthWest(),
results[0].geometry.viewport.getNorthEast());
}
else
{
alert("NOT SUCCESS 2");
}
showGMap(latlng, abstract_location);
});
}
else
{
geocoder.geocode( {'address': 'Vilnius Region, Lithuania'}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var latlng = results[0].geometry.location;
var abstract_location = new google.maps.LatLngBounds(
results[0].geometry.viewport.getSouthWest(),
results[0].geometry.viewport.getNorthEast());
showGMap(latlng, abstract_location);
}
else
{
alert("NOT SUCCESS 3");
}
});
}
}
Nor Chromium nor Opera does not give me ANY errors, nor javascript exceptionaly, nor in general.
So the problem is in success function. Because it even does not give me alert(typesToDisplay.length) [as suggested by Stuart in the comments] - it means that there is no alert at all - in case of error function I get the aswer 4 and thus i can see my generated HTML.
In case of success function there is just empty (without any appended childs) #types .
I do not see what could be causing success function to be NOTSUCCESS (:))
Ok, so i have figured it out - it was pretty simple though...
The Geolocation data which you get is an address, so bounds are very small, you have to extract city with reverse geocoding (results[6].formatted_address) and then you geocode that reverse geocode (so confused though Geocoding -> reverse -> again geocode) and then it works!
So the problem was at geocoding (haven't thought that bounds of address is not the whole city (that should have been obvious in the first place, but was not).
HTML5 geocoding could have the info about the city (not only lan and lng, firefox has something, but that's only firefox, not the whole HTML5), but i do not know if it would be good or not (lack of my personal knowlede at the moment in this specific field)
So if anyone does get to something similar -> check the bounds ;)
Thank you for your comments and for your view's.

Categories