How to center Google Map on a country by name - javascript

I'm using the Google Maps API (v2) and would like to center the map onload to a country (for example england).
At the moment i center the map using:
map.setCenter(new GLatLng( 43.907787,-79.359741), 9);
But this obviously requires longitude and Latitude.
Any way to do this by inserting a name of a country?

var country = "United States"
var map = new GMap2($("#map")[0]);
map.setUIToDefault();
var geocoder = new GClientGeocoder();
geocoder.getLatLng(country, function (point) {
if (!point) {
// Handle error
} else {
map.setCenter(point, 8, G_PHYSICAL_MAP);
}
});

You need to geocode the address first:
var geocoder = new google.maps.Geocoder();
var location = "England";
geocoder.geocode( { 'address': location }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
} else {
alert("Could not find location: " + location);
}
});

Turning a location name or address into a latitude/longitude like this is called geocoding. Google Maps API now includes this capability: see http://code.google.com/apis/maps/documentation/services.html#Geocoding
They include a sample application where you can type in an address, and it does work to simply type a country name. I don't know if they are going to the exact center of the country.

Related

(Google Map API) Geocode was not successful for the following reason: REQUEST_DENIED

I am new to this place and I desperately need help from experts here! D=
I tried to make a page that can generate dynamic numbers of google map. The webpage, however, keep showing Geocode was not successful for the following reason: REQUEST_DENIED.
I double checked my google API console and confirmed that the geocoding API and Javascript API are enabled. (I literally enabled all Google map API in the list...)
My Google Map API List
Can someone please take a look and tell me why? T_T
//------------------------------------------------\\
Below is my javascript and html button:
Javascript:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=APIkey&callback=initMap"
type="text/javascript"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=mapAddress"
type="text/javascript"></script>
<!-- &callback=mapAddress -->
<script>
function mapAddress(mapElement, address) {
var geocoder = new google.maps.Geocoder();
// alert(mapElement);
// alert(address);
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var mapOptions = {
zoom: 17,
center: results[0].geometry.location,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById(mapElement), mapOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
HTML(Supposed to be php variable):
<button type="button" class="button_mapAPI" id="address_<?php echo $case["id"]; ?>" value="<?= $case['location_detail'] ?>" onclick="mapAddress('map1', 'Hong Kong')"/>Map Refresh</button>
Did you enable the Billing for API Key? Google Maps is no longer free. You have to associate a credit card so that you can get billed if your site has requests that exceed the $200 credit they give you monthly for free.
First of all, the problem was loading the scripts as async, remove it..
try that jsfiddle with your API KEY
(function(){
let mapElement = 'map';
let address = 'SPAIN';
geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var mapOptions = {
zoom: 17,
center: results[0].geometry.location,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById(mapElement), mapOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
})();
#map {
width: 100%;
height: 350px;
}
<script src="https://maps.googleapis.com/maps/api/js?key=APIKEY" type="text/javascript"></script>
<div id="map"></div>
Nead to enable geocoding api that convert address to coordinates and it is a bit pricier, use coordinates instead of address and no need for Geocoding API

Request main road / curbside StreetView panoramas instead of back alleys from API

Is there a way to request main road Google StreetView panorama data instead of back alley panorama data for a given location (latitude/longitude)?
I'm using the Google Maps Javascript API to retrieve a street view panorama from a home address supplied by our users. It works quite well for most addresses I've tried, but I'm noticing a lot of properties in California also have street views for back alleys, and the API seams to be consistently returning the back alley panorama instead of the main road (front of property) panorama.
I don't want to show the user a back alley panorama of their home, but instead the main road panorama. If I lookup the same address on maps.google.com I see the front of the house, but when I request the same address through the API I get the back alley.
The process I'm currently using is:
Geocode address
Get panorama given the geocode location (lat/long)
Compute heading and display panorama on page
Test Addresses:
325 S Peck Dr, Beverly Hills, CA, USA, 90212
333 S Rodeo Dr, Beverly Hills, CA, USA, 90212
Any ideas or suggestions would be greatly appreciated. Thanks!
Use the directions service to get directions from the desired address to itself. Use that location instead of the geocoder result for the street view location. Use the geocoder result (hopefully a ROOFTOP accuracy result) for the place to look "at".
related question: Facing the targeted building with Google StreetView
Examples:
325 S Peck Dr, Beverly Hills, CA, USA, 90212
333 S Rodeo Dr, Beverly Hills, CA, USA, 90212
code snippet:
var sv = new google.maps.StreetViewService();
var geocoder = new google.maps.Geocoder();
var directionsService = new google.maps.DirectionsService();
var panorama;
var address = "333 S Rodeo Dr, Beverly Hills, CA, USA, 90212";
var myLatLng;
function initialize() {
panorama = new google.maps.StreetViewPanorama(document.getElementById("pano"));
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
myLatLng = results[0].geometry.location;
// find a Streetview location on the road
var request = {
origin: address,
destination: address,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, directionsCallback);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function processSVData(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
panorama.setPano(data.location.pano);
var heading = google.maps.geometry.spherical.computeHeading(data.location.latLng, myLatLng);
panorama.setPov({
heading: heading,
pitch: 0,
zoom: 1
});
panorama.setVisible(true);
} else {
alert("Street View data not found for this location.");
}
}
function directionsCallback(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var latlng = response.routes[0].legs[0].start_location;
sv.getPanoramaByLocation(latlng, 50, processSVData);
} else {
alert("Directions service not successfull for the following reason:" + status);
}
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="pano" style="width: 425px; height: 400px;float:left"></div>

How to use the JavaScript API V3 Client Geocoder to geocode postal codes

I have the following code below that geocodes address from a google spreadsheet. I have research this but I can't find a good example of how to just geocode postal codes in the US. Does anyone know a good example.
Thanks
function geocode(address) {
var response = UrlFetchApp.fetch("http://maps.googleapis.com/maps/api/geocode/json?address="+escape(address)+"&sensor=false");
var respObj=Utilities.jsonParse(response.getContentText());
var loc = {lat:NaN,lng:NaN};
try {
loc = respObj.results[0].geometry.ZIP_CODE
} catch(e) {
Logger.log("Error geocoding: "+address);
}
return loc;
}
https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple?csw=1
Try putting in a zip code it works.
This is the relevant code
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 API v3 Geodecoder country

How would you limit your search to a county in below query?
geocoder = new google.maps.Geocoder();
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
});
I've tried formatting an object like this:
{
address: '389 george st, sydney'
county: au
}
But if I search for 'poo' for instance India comes up in the results. How would I limit to only search in Australia?
You need to do region code biasing.
The query must be specific to the area you want to search.
This is the example given by Google.
https://developers.google.com/maps/documentation/javascript/examples/geocoding-region-es

How do import a CSV file into the javascript for a webapp so that i can place address markers on a google maps canvas?

So I am a bit new to javascript and the Google maps API's. Currently I can place a marker given a single hard coded address variable called codeAddress.
codeAddress("99362");
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);
}
});
}
The problem is that I need to be able to place multiple markers based on location and need to be able to parse address data from a CSV file or from an sql database.
thanks for the help.
I've used the jquery-csv plugin to process csv files.
If you can give more specifics on where this csv file is coming from, and how it will be loaded, I can give info on how you can convert this into a javascript array. Will this file be on the server already? If so, then it would make more sense to do some server side processing to read the file.
The following shows how to modify your code to work with an array of multiple addresses:
var addresses = ["99362", "01010", "12345"];
jQuery.each(addresses, function(index, address) {
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// we only need to center the map the first time
if (index == 0)
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);
}
});
})

Categories