How to use Address instead of Lat/Long in Google Map API
You have to use the Geocoding API. An example to make an Address to Lat/lng:
doGeocode: function (address, postal_code, callback) {
console.log("TEST: "+address.toString());
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address,
'componentRestrictions': {
'postalCode': postal_code,
'country': 'de'
}
}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
callback(results);
} else {
//Error handling
alert('Geocode was not successful for the following reason: ' + status);
}
});
Note: The address can also contain the houseNumber but enter a whitespace.
There is also a reverse Way to get Addresses from Lat/lng. Just in case some needs that:
reverseGeocoder: function (lat, lng, callback) {
var geocoder = new google.maps.Geocoder;
var addressComponents = {};
geocoder.geocode({
'location': {
lat:lat,
lng: lng
}
}, function (results, status){
if(status === google.maps.GeocoderStatus.OK){
if (results[1]) {
var result = results[0].address_components;
for (var i = 0; i < result.length; i++) {
if (result[i].types[0] == "route") {
console.log(result[i].long_name);
addressComponents.route = result[i].long_name
}
if (result[i].types[0] == "street_number") {
console.log(result[i].long_name);
addressComponents.street_number = result[i].long_name
}
if (result[i].types[0] == "locality") {
console.log(result[i].long_name);
addressComponents.locality = result[i].long_name
}
if (result[i].types[0] == "postal_code") {
console.log(result[i].long_name);
addressComponents.postal_code = result[i].long_name
}
}
callback(addressComponents);
} else {
alert('No information found.');
}
}else {
alert("Die geolocation abfrage konnte leider nicht ausgeführt werden. "+status);
}
});
From the first function above you will get the Lat/lng.
Then simply use a function like this:
var newMarkers = []; //Global marker array
marker: function (lat, lng) {
console.log("new marker");
//console.log("LAT: "+lat+ "LNG: "+lng);
var marker = new google.maps.Marker({
position: {lat: lat, lng: lng},
icon: icon,
map: map
});
markers.push(marker);
marker.addListener('click', function () {
//InfoWindow or whatever u want
});
map.setCenter({lat: lat, lng: lng});
map.setZoom(16);
},
Using Address Instead Of Longitude And Latitude With Google Maps API
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>
How do I use Address rather than Longitude and Latitude in google maps?
Checkout this code here, it uses 'San Diego, CA' to start 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>
Source of answer: Using Address Instead Of Longitude And Latitude With Google Maps API
Precisely what you need to do is, use Geocoding to convert "Text Address" into respective latitude and longitude and then use those values to feed Google Map API.
You can read more about Google Geocoding in maps documentation https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingRequests
and a Sample code from documentation
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Geocoding service</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
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-canvas'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
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);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map-canvas"></div>
</body>
</html>
gmaps.js using address instead of latitude longitude
Use the Geocoder to translate an address into geographic coordinates that can be used on a map.
Related question: Using Address Instead Of Longitude And Latitude With Google Maps API
proof of concept fiddle
Example with GMaps.js:
code snippet:
function initialize() {/*Maps*/var map = new GMaps({ div: '.map', lat: 0, lng: 0, zoom: 0});
GMaps.geocode({ address: "Oradell, NJ", callback: function(results, status) { if (status == 'OK') { var latlng = results[0].geometry.location; map.fitBounds(results[0].geometry.viewport); map.addMarker({ lat: latlng.lat(), lng: latlng.lng() }); } }});
}google.maps.event.addDomListener(window, "load", initialize);
body, html { width: 100%; height: 100%;}
.map { width: 100%; height: 100%;}
<script src="https://maps.googleapis.com/maps/api/js"></script><script src="https://hpneo.github.io/gmaps/gmaps.js"></script><div class="map"></div>
Can I provide addresses instead of latitude and longitude to Google Maps?
Yes of course. That can be done very easily, using the Geocoding Services provided by the Google Maps JavaScript API. Consider the following example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps Geocoding Demo 1</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 400px; height: 300px;"></div>
<script type="text/javascript">
var address = 'London, UK';
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.TERRAIN,
zoom: 6
});
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
map.setCenter(results[0].geometry.location);
}
});
</script>
</body>
</html>
Screenshot:
You can simply substitute 'London, UK'
from the address
variable to any location that supports geocoding in Google Maps.
Use address to create route with google maps (without latitude and longitude)
I think you need to escape the non-ASCII part of the url string. Call the method addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
on your studioAddress
before inserting in into the url string.
Update:
Since you are using a String
optional (aka String?
/ Optional<String>
) in your interpolation (see this question that I mentioned in the comment):
let str = "comgooglemaps://?daddr=\(self.studioInfoFromDetail?.studioAddress)&directionsmode=driving"
You will get:
"comgooglemaps://?daddr=\Optional(<... your string ...>)&directionsmode=driving"
Thus you need to unwrap the optional before using it.
if let address = self.studioInfoFromDetail?.studioAddress {
let str = "comgooglemaps://?daddr=\(address)&directionsmode=driving"
}
You can also force unwrap (with an operator !
), but I would not recommend doing that.
How to convert an address to longitude and latitude then display a map on the page
As mentioned above the code needed to be put inside of my callback function.
<script>
function initMap(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
}
console.log(latitude);
console.log(longitude);
var myLatLng = {lat: latitude, lng: longitude};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCY2buDtbYIot8Llm_FkQXHW36f0Cme6TI&callback=initMap">
</script>
Google Map Address from latitude and longitude
Fetching the associated address from a coordinates is called Reverse Geocoding
The Google Maps API provides reverse geocoding in the javascript API and as a web service.
The Google Maps service is not intended for bulk use. Your best option is to store the address in your database along with the coordinates as Reverse Geocoding is not always reliable.
Related Topics
How to Add Conditional Attribute in Angular 2
Canvas.Todataurl() Securityerror
JavaScript - Get Minutes Between Two Dates
Regarding Promises/A+ Specification, Differencebetween the Terms "Thenable" and "Promise"
How to Call Loading Function with React Useeffect Only Once
Need to Escape a Special Character in a Jquery Selector String
How to Watch for Array Changes
Escaping Strings in JavaScript
Prevent Requirejs from Caching Required Scripts
(![]+[])[+[]]... Explain Why This Works
Set Additional Data to Highcharts Series
Jquery Checkbox Checked State Changed Event
Can a PDF File's Print Dialog Be Opened with JavaScript
Recursive Matching with Regular Expressions in JavaScript