Google maps get latitude and longitude having city name? - javascript

I want to get latitude and longitude of a city by providing the API with the city name. It should work for most cities regardless how the user inputs the city.
For example:
City can be 'miami, US' or city can be 'miami, united states'
How do I print its latitude?

You can find the code jsfiddled here : http://jsfiddle.net/YphZw/
or below :
$("#btn").click(function(){
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': 'miami, us'}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("location : " + results[0].geometry.location.lat() + " " +results[0].geometry.location.lng());
} else {
alert("Something got wrong " + status);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
</head>
<body>
<input id="btn" type="button" value="search for miami coordinates" />
</body>
</html>
If you want more examples for the Javascript API, try this link : https://developers.google.com/maps/documentation/javascript/examples/
The code I wrote is inspired from the geocoding-simple sample.
Regards.
EDIT 1:
You can achieve it using an non-official PHP library. Check this example :
http://www.bradwedell.com/phpgooglemapapi/demos/geocoding.php
(The code is at the bottom=

You can use Google's geocoding service, e.g.,
http://maps.googleapis.com/maps/api/geocode/xml?address=Miami+FL&sensor=false
That gives you back georeferenced data in a variety of formats (JSON, XML, etc). In any event, the location is definitely in the returned data block.
The API docs are at:
https://developers.google.com/maps/documentation/geocoding/

Update per comment below: Doesn't work after July 2018.
This seems needlessly complicated. Here's an example "nearby events" map. It will take City, States, convert them to latLng coords, and put markers on a map:
// Nearby Events with Google Maps
window.nearbyEventsMap = () => {
const centerOfUS = {
lat: 37.09024,
lng: -95.712891
}
// Create a map object and specify the DOM element for display.
const map = new google.maps.Map(document.querySelector('#nearby_events_map'), {
center: centerOfUS,
scrollwheel: false,
zoom: 4
})
// Create a marker and set its position.
const geocoder = new google.maps.Geocoder()
// Filter out duplicate cityStates
let cityStates = {}
document.querySelectorAll('.nearby_event_city_state').forEach(event => {
cityStates[event] = event.innerText
})
// `cityState` is in the format of "City, State". It's not picky about state being a word or the abbreviation.
for (const cityState in cityStates) {
const location = cityStates[cityState]
geocoder.geocode({
address: location
}, function (results, status) {
if (status === 'OK') {
const result = results[0].geometry.location
const lat = result.lat()
const lng = result.lng()
const latLng = {
lat,
lng
}
return new google.maps.Marker({
map: map,
position: latLng
})
}
})
}
}
// /Nearby Events with Google Maps
Make sure to include your <script> tags.
<script src="/dist/js/main.js"></script>
<!-- We're loading this after the main.js script so the callback from main.js will be available to it. -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=nearbyEventsMap"></script>
StackOverflow please join everyone else and get GitHub markdown with syntax highlighting...

Related

Why wont Google Maps API Key recognise my referrer URL?

I have a html file on my website domain (devodeliver.co.uk) which calls on my API Key with the code.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY-KEY"></script>
In the Developers Console I have tried adding every combination of my domain URL as you can see below
But when I load my site it shows the map for a millisecond then returns with the error "Google Maps API error: InvalidKeyMapError https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key-map-error_.bb # MY-KEY:32" - basically saying I haven't given my website permission to access that API Key. But even if I don't set any referrers, it come back with the same error message. I've also waited way over 5 minutes for the API to take affect. Please, what am I doing wrong?! I've spent almost 16 hours trying to figure this out & I can't seem to for the life of me. HELPPPP!
Full HTML code:
<html>
<head>
<style type="text/css">
#map
{
height:400px;
width:400px;
display:block;
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB7-LTLEupUWBJBWl1GpOWPwkMvxzf8itQ"></script>
<script type="text/javascript">
function getPosition(callback) {
var geocoder = new google.maps.Geocoder();
var postcode = document.getElementById("postcode").value;
geocoder.geocode({'address': postcode}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
callback({
latt: results[0].geometry.location.lat(),
long: results[0].geometry.location.lng()
});
}
});
}
function setup_map(latitude, longitude) {
var _position = { lat: latitude, lng: longitude};
var mapOptions = {
zoom: 16,
center: _position
}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var marker = new google.maps.Marker({
position: mapOptions.center,
map: map
});
}
window.onload = function() {
setup_map(51.5073509, -0.12775829999998223);
document.getElementById("form").onsubmit = function() {
getPosition(function(position){
var text = document.getElementById("text")
text.innerHTML = "Marker position: { Longitude: "+position.long+ ", Latitude:"+position.latt+" }";
setup_map(position.latt, position.long);
});
}
}
</script>
</head>
<body>
<form action="javascript:void(0)" id="form">
<input type="text" id="postcode" placeholder="Enter a postcode">
<input type="submit" value="Show me"/>
</form>
<div id="map"></div>
<div id="text"></div>
</body>
</html>
Here, when I tested it, it gives me the error "Google Maps API error: ApiNotActivatedMapError" on the JS console.
Take a look for this issue on: https://developers.google.com/maps/documentation/javascript/error-messages#deverrorcodes
When you use a library or service via the Maps-Javascript-API, and use a key, you need to activate the Google Maps JavaScript API .
Make sure to activate the Google Maps JavaScript API for your project.
Also,
take a look on this other topic about Enable the Google Maps Jvascript API: Google Map error: InvalidKeyOrUnauthorizedURLMapError

How to Get Current Address accurately using Google Maps?

Im trying to get my current location but the problem is the address which the marker points is only the nearest street where I am now. How can I get my place accurately?
Heres the screen shot. Thanks in advance :)
Click here
<input type="button" value="Show Location" onclick="showlocation()"/>
<br/>
Latitude: <span id="latitude">..</span> <br>
Longitude: <span id="longitude">..</span><br>
Address: <span id="add">..</span><br>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function showlocation(){
navigator.geolocation.watchPosition(callback);
}
function callback(position){
document.getElementById('latitude').innerHTML=position.coords.latitude;
document.getElementById('longitude').innerHTML=position.coords.longitude;
var geocoder = new google.maps.Geocoder();
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var latLng = new google.maps.LatLng(latitude,longitude);
geocoder.geocode({
latLng: latLng
},
function(responses)
{
if (responses && responses.length > 0)
{
address(responses[0].formatted_address);
}
else
{
alert('Not getting Any address for given latitude and longitude.');
}
}
);
}
function address(str)
{
document.getElementById('add').innerHTML = str;
}
</script>
Use Geolocation API. To obtain your current location, you can call the getCurrentPosition() method. This initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information.
When the position is determined, the defined callback function is executed. You can optionally provide a second callback function to be executed if an error occurs. A third, optional, parameter is an options object where you can set the maximum age of the position returned, the time to wait for a request, and if you want high accuracy for the position.
This documentation and example might help you.

Here Maps API - Basic place display (placeId)

I implemented the map on web page using JavaScript API, and now I want to show the basic information about some location. In JavaScript API documentation, I found a part of which is called "Basic place display" in Places Components section, but there is an example of how to render information using placeId.
I need to be able to retrieve information using location coordinates if it is possible. I tried to display information using PHP code that define coordinates for some location on the map instead of using placeId, but it's not working.
This is an example of code that I used:
var basicPlace = new nokia.places.widgets.Place({
placeId: PHP code instead of placeId.
*exp: [<?php code;?>, <?php echo code;?>],*
targetNode: "map",
template: "nokia.blue.place"
});
Is it possible to solve the problem like that, or there is a method that does not involve placeId.
Links: Here Developer, Here JavaScript API
If you read the nokia.places.widgets.Place documentation, you will see that placeId is a mandatory parameter. It is in effect the primary key for the place information that is held by HERE. You will therefore need to make another request using the JavaScript API prior to display in order to obtain the placeId so you can show your place details. The obvious thing to do here is to make a category request first, and store the placeId with each marker as shown below:
// Function for receiving search results from places search and process them
var processResults = function (data, requestStatus, requestId) {
var i, len, locations, marker;
if (requestStatus == "OK") {
locations = data.results ? data.results.items : [data.location];
if (locations.length > 0) {
for (i = 0, len = locations.length; i < len; i++) {
// Add a marker and store the placeId
marker = new nokia.maps.map.StandardMarker(locations[i].position,
{ text: i+1 ,
placeId : locations[i].placeId});
resultSet.objects.add(marker);
}
}
});
// etc.. etc...
The second part is to add the click listener which displays an infobubble and populates the Place Widget using the stored placeId:
resultSet.addListener("click" , function(evt) {
infoBubbles.openBubble("<div id='basicPlaceContainer'></div>",
evt.target.coordinate);
var basicPlace = new nokia.places.widgets.Place({
placeId: evt.target.placeId,
targetNode: "basicPlaceContainer",
template: "nokia.blue.bubble"
});
}, false);
The complete working example can be seen below:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=EmulateIE9; IE=10" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Nokia Maps API for JavaScript Example: Search by category</title>
<meta name="description" content="Search by category"/>
<script type="text/javascript" charset="UTF-8" src="http://js.cit.api.here.com/se/2.5.3/jsl.js?with=all"></script>
</head>
<body>
<div id="mapContainer" style="width:540px; height:334px;"></div>
<script type="text/javascript" id="exampleJsSource">
/* Setup authentication app_id and app_code
*/
nokia.Settings.set("app_id", "YOUR APP ID");
nokia.Settings.set("app_code", "YOUR APP CODE");
// Use staging environment (remove the line for production environment)
nokia.Settings.set("serviceMode", "cit");
// Get the DOM node to which we will append the map
var mapContainer = document.getElementById("mapContainer");
// Create a map inside the map container DOM node
var map = new nokia.maps.map.Display(mapContainer, {
// Initial center and zoom level of the map
center: [52.51, 13.4],
zoomLevel: 10,
components: [
new nokia.maps.map.component.Behavior()
]
});
this.infoBubbles = new nokia.maps.map.component.InfoBubbles();
map.components.add(infoBubbles);
var searchCenter = new nokia.maps.geo.Coordinate(52.51, 13.4),
searchManager = nokia.places.search.manager,
resultSet;
// Function for receiving search results from places search and process them
var processResults = function (data, requestStatus, requestId) {
var i, len, locations, marker;
if (requestStatus == "OK") {
locations = data.results ? data.results.items : [data.location];
if (locations.length > 0) {
if (resultSet) map.objects.remove(resultSet);
resultSet = new nokia.maps.map.Container();
resultSet.addListener("click" , function(evt) {
infoBubbles.openBubble("<div id='basicPlaceContainer'></div>", evt.target.coordinate);
var basicPlace = new nokia.places.widgets.Place({
placeId: evt.target.placeId,
targetNode: "basicPlaceContainer",
template: "nokia.blue.bubble"
});
}, false);
for (i = 0, len = locations.length; i < len; i++) {
marker = new nokia.maps.map.StandardMarker(locations[i].position,
{ text: i+1 ,
placeId : locations[i].placeId});
resultSet.objects.add(marker);
}
map.objects.add(resultSet);
map.zoomTo(resultSet.getBoundingBox(), false);
} else {
alert("Your search produced no results!");
}
} else {
alert("The search request failed");
}
};
// Make a place search request
var category = "eat-drink";
map.addListener("displayready", function () {
searchManager.findPlacesByCategory({
category: category,
onComplete: processResults,
searchCenter: searchCenter
});
});
</script>
</body>
</html>
The result can be see below:

Google Maps geocoder does not find places that are not exact addresses, unlike the Google Maps website

I'm trying to use the Google Maps geocoding service. I copied the code and it seems to find addresses fine (for example "13 Marine Terrace Aberystwyth") but not other places like "Rummers Wine Bar, Aberystwyth" even though the actual Google Maps website has no problem with them at all.
This is my code, slightly modified to be for the Aberystwyth area but otherwise copied form https://developers.google.com/maps/documentation/javascript/tutorial
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="styles.css" />
<script type="text/javascript"
/*you can use https if you want it secure!!! set java scrip sensor to true and read from gps!*/
src="http://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXo-tdDimvjIs&sensor=false&region=GB">
</script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(52.4156, -4.0829);
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
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);
}
function code ()
{document.write(results[0].geometry.location);}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width: 320px; height: 480px;"></div>
<div>
<input id="address" type="textbox" value="aberystwyth">
<input type="button" value="Encode" onclick="codeAddress()">
</div>
</script>
<script type="text/javascript">
code();
</script>
</body>
This is a link to it: http://users.aber.ac.uk/avh9/thesite/geocodeaber.html
Can anyone tell me why and how to fix it? or any alternative for geocoding....
There's a library called Places Library within Google Maps API. You can use its search() nearbySearch() or textSearch() methods to search for POIs and landmarks.

Can I know if a location on Google Maps isn't found when using this lazy method?

I'm showing a Google Map based on a street address supplied from an outside source.
My JavaScript is very simple, and I build the link like so
var googleMap = 'http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=' + address + '&ie=UTF8';
This is quick and easy, and works. But some of the incoming addresses aren't exactly addresses (they include some stuff which shouldn't be there).
When Google Maps can't make heads or tails of the address, it defaults to showing a map of USA. Unfortunately, I'm in Australia.
Is there any way using this lazy method to know if Google Maps couldn't match the address, or can I show Australia by default?
... or do I need to look at the API?
What about using maps.google.com.au? Note that the parameters might be a bit different.
http://maps.google.com.au/maps?q=Melbourne
http://maps.google.com.au/maps?q=Something-Garbage-That-Does-Not-Exist
You could also use the Maps API, as you suggested. Something like that would be very easy to do:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps Geocoding Default Location</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 = 'Melbourne, Australia';
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.TERRAIN,
center: new google.maps.LatLng(-25.50, 135.00),
zoom: 3
});
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:
And another screenshot if you were to use address = 'Something Garbage That Does Not Exist':

Categories

Resources