Using Address Instead Of Longitude And Latitude With Google Maps API

JavascriptGoogle MapsGoogle Maps-Api-3Latitude LongitudeStreet Address

Javascript Problem Overview


I've heard that it is possible to submit an Address instead of Longitude and Latitude and this would be much more feasible for my system. The user has to input their address when creating their profile and their profile afterwards will then display a Google Maps of their house. I currently have the Google Maps API working perfectly with Longitude and Latitude:

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="css.css" />
    <title>Login Page</title>

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
  html { height: 100% }
  body { height: 100%; margin: 0; padding: 0 }
  #map-canvas { height: 100% }
</style>
<script type="text/javascript"
  src="https://maps.googleapis.com/maps/api/js?key=MYKEY&sensor=false">
</script>
<script type="text/javascript">
  function initialize() {
    var mapOptions = {
  center: new google.maps.LatLng(52.640143,1.28685),
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map"),
        mapOptions);

var marker = new google.maps.Marker({
	position: new google.maps.LatLng(52.640143,1.28685),
	map: map,
	title: "Mark On Map"
});
  }
  google.maps.event.addDomListener(window, 'load', initialize);
</script>

</head>

Please could somebody assist me to alter my code so that it enables the Google Maps API to request an Address in its place because I want to read the Address of the user directly from mySQL database.

Javascript Solutions


Solution 1 - Javascript

See this example, initializes the map to "San Diego, CA".

Uses the Google Maps Javascript API v3 Geocoder to translate the address into coordinates that can be displayed on the map.

<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
  var geocoder;
  var map;
  var address ="San Diego, CA";
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
    mapTypeControl: true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    if (geocoder) {
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
          map.setCenter(results[0].geometry.location);

            var infowindow = new google.maps.InfoWindow(
                { content: '<b>'+address+'</b>',
                  size: new google.maps.Size(150,50)
                });
    
            var marker = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map, 
                title:address
            }); 
            google.maps.event.addListener(marker, 'click', function() {
                infowindow.open(map,marker);
            });

          } else {
            alert("No results found");
          }
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }
  }
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
 <div id="map_canvas" style="width:100%; height:100%">
</body>
</html>

working code snippet:

var geocoder;
var map;
var address = "San Diego, CA";

function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var myOptions = {
    zoom: 8,
    center: latlng,
    mapTypeControl: true,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
    },
    navigationControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  if (geocoder) {
    geocoder.geocode({
      'address': address
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
          map.setCenter(results[0].geometry.location);

          var infowindow = new google.maps.InfoWindow({
            content: '<b>' + address + '</b>',
            size: new google.maps.Size(150, 50)
          });

          var marker = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map,
            title: address
          });
          google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map, marker);
          });

        } else {
          alert("No results found");
        }
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
}
google.maps.event.addDomListener(window, 'load', initialize);

html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
}

<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" ></div>

Solution 2 - Javascript

Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers or position the map.

Would this be what you are looking for: Contains sample code
https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingRequests

Solution 3 - Javascript

You can parse the geolocation through the addresses. Create an Array with jquery like this:

//follow this structure
var addressesArray = [
  'Address Str.No, Postal Area/city'
]

//loop all the addresses and call a marker for each one
for (var x = 0; x < addressesArray.length; x++) {
  $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addressesArray[x]+'&sensor=false', null, function (data) {
    var p = data.results[0].geometry.location
    var latlng = new google.maps.LatLng(p.lat, p.lng);
    //it will place marker based on the addresses, which they will be translated as geolocations.
    var aMarker= new google.maps.Marker({
      position: latlng,
      map: map
    });
  });
}

Also please note that Google limit your results if you don't have a business account with them, and you my get an error if you use too many addresses.

Solution 4 - Javascript

var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
  zoom: 8,
  center: latlng
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}

function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == '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);
  }
});
}

<body onload="initialize()">
 <div id="map" style="width: 320px; height: 480px;"></div>
 <div>
   <input id="address" type="textbox" value="Sydney, NSW">
   <input type="button" value="Encode" onclick="codeAddress()">
 </div>
</body>

Or refer to the documentation https://developers.google.com/maps/documentation/javascript/geocoding

Solution 5 - Javascript

Thought I'd share this code snippet that I've used before, this adds multiple addresses via Geocode and adds these addresses as Markers...

var addressesArray = [
  'Address Str.No, Postal Area/city',
  //follow this structure
]
var map = new google.maps.Map(document.getElementById('map'), {
  center: {
    lat: 12.7826,
    lng: 105.0282
  },
  zoom: 6,
  gestureHandling: 'cooperative'
});
var geocoder = new google.maps.Geocoder();
for (i = 0; i < addressArray.length; i++) {
  var address = addressArray[i];
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status === 'OK') {
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location,
        center: {
          lat: 12.7826,
          lng: 105.0282
        },
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionedwoollardView Question on Stackoverflow
Solution 1 - JavascriptgeocodezipView Answer on Stackoverflow
Solution 2 - JavascriptPavan K MuttView Answer on Stackoverflow
Solution 3 - JavascriptSidiusView Answer on Stackoverflow
Solution 4 - JavascriptThilinaView Answer on Stackoverflow
Solution 5 - JavascriptbstoneView Answer on Stackoverflow