Search code examples
databasegoogle-mapsgoogle-maps-api-3google-geocoder

Converting database of coordinates to physical addresses


I'm trying to make a real estate agency website and got an idea of saving addresses as coordinates to database (because text addresses can be difficult)

So I have two main questions:

1) Is it possible to search objects by street if their addresses are saved as coordinates? And how difficult is it? Maybe you could give a working example in any web-programming language or advise a good walkthrough.

2) Is it a feasible approach? Maybe it has awful drawbacks I don't see.


Solution

  • Yes, it is in fact possible to convert the latitude and longitude of a location into an address. This is achieved through the Google Maps Reverse Geocoding service through the Javascript API.

    Take a look at this site to read up a bit more on reverse geocoding and how you could make it work for your project.

    Here is a code sample of a reverse geocoding request: Live example here

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