I am using the basic functionality of Google Maps Javascript API
Code sample from google :
https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
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);
So as you can tell, when we type a street name, even if we have several results, the sample above is just showing one. I already changed that to loop throught all results and it works fine.
My questions are:
The geocoder.geocode results are sorted by any criteria?
If the answer is yes, is it possible to get the results sorted by most relevant / near place of the current user location ? (I will pass the current user location).
Thanks a lot
Closest thing that I know off is using region biasing: https://developers.google.com/maps/documentation/geocoding/intro#RegionCodes
You're using the wrong API for this, try using the Google Places API. This sorts by popularity (preferred).
Or you can use some code to loop through the results and find the distance from the original location. Then you can sort by distance (works, but I think popularity is what you want)
Related
i had problem on saving the address in variable when i use google map api
i try to save it in global variable and then calling these variable with console.log
<script>
var x;
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(27.191315760031543, 31.189079340815315),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
google.maps.event.addListener(map, 'click', function (e) {
var latlng = new google.maps.LatLng(e.latLng.lat(), e.latLng.lng());
var geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
alert("Location: " + results[1].formatted_address + "\r\nLatitude: " + e.latLng.lat() + "\r\nLongitude: " + e.latLng.lng());
x=results[1].formatted_address;
}
}
});
});
}
console.log(x);
</script>
Geocoding Service: You must use an API key to authenticate each request to Google Maps Platform APIs. For additional information, please refer to http://g.co/dev/maps-no-account For more information on authentication and Google Maps JavaScript API services please see: https://developers.google.com/maps/documentation/javascript/get-api-keyenter code here
It's required to include an API key to authenticate all Maps API requests. As per the error you provided, it indicates that there is no API key included in the script that loads the JavaScript API.
Kindly include the API key like this:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY">
</script>
Then replace the text YOUR_API_KEY with your valid API key.
Please also note that it is recommended to initialize your map by specifying a callback parameter. Please see more info about that here.
Ive been working on a Google Maps application and have hit a hurdle due to a lack of knowledge in js me thinks?!
So... here's my JSON object
{"pickuppoint0":"LE9 8GB","pickuppoint1":"LE2 0QA","pickuppoint2":"LE3 6AF","pickuppoint3":"LE2 8GB","pickuppoint4":"LE8 8TE","pickuppoint5":"LE2 2GB","pickuppoint6":"LE1 6AF"}
And here's a loop through the JSON object...
$.each(alltravelgroups, function(k, v){
for(var i=0; i < boxes.length; i++){
var bounds = boxes[i];
if(bounds.contains(getLatLng(v))){
alert("im here");
}
}
});
And here's my getLatLng() method I've created...
function getLatLng(pickuppoint) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': pickuppoint}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
return results[0].geometry.location
} else {
alert('getLatLng Geocode was not successful for the following reason: ' + status);
}
});
}
Now... what I'm trying to do is simply take the value from each key/value pair and produce a LatLng object that can then be used within the "bounds.contains()" method for searching within the bounds box provided by the RouteBoxer class.
The problem I'm facing is the value returned by the getLatLng method is "undefined" when using alert(getLatLng(v)) and should just be a 'location' containing both latitude and longitde? Anyone able to point what I'm doing wrong?
Please refer the link below.
http://jsfiddle.net/y829C/13/
var mapOptions = {
center: new google.maps.LatLng(-33.8665433, 151.1956316),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
In the above code, semicolon is missing in return results[0].geometry.location.
I am pulling is lat long points from a database, combine them, then use reverse lookup to place markers on my map. All the markers get placed on the map, but they are just a little off. I then go to maps.google.com and place the points into the search bar and they work perfectly. Any suggestions? Thank you! The funciton is below:
var lat = resultP[i].get("lat");
var log = resultP[i].get("long");
var latlng = new google.maps.LatLng(lat, log);
geocoder.geocode( { 'latLng': latlng}, 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);
} //end else
Apologies if I misunderstood something, but I don't see why you need to geocode the coordinates.
Geocoding is the process of turning an address into coordinates, or the other way around. You don't need to geocode your coordinates if you already have them. The whole point of geocoding is to put them on the nearest road.
To display a marker on the map you can just skip the geocoding and do this:
var lat = resultP[i].get("lat");
var log = resultP[i].get("long");
var latlng = new google.maps.LatLng(lat, log);
var marker = new google.maps.Marker({
map: map,
position: latlng
});
I've been cobbling together various bits of code from around the internet (including StackOverflow) and I've got a working map (almost) which geocodes postcodes from an array and creates infowindows for each one.
Two problems:
1) my info windows, which should take their text from another array, always use the last array value
2) i can't get the map to center automatically. I'm using a bit of code which has worked in other circumstances, but it doesn't in my code.
The code is fairly self-explanatory:
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById('map'), {
//zoom: 10,
//center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var postcodes = [
"EH14 1PR",
"KY7 4TP",
"IV6 7UP"
];
var descriptions = [
"Slateford",
"Cortachy",
"Marybank"
];
var markersArray = [];
var infowindow = new google.maps.InfoWindow();
var marker, i, address, description;
for(var i = 0; i < postcodes.length; i++) {
address = postcodes[i];
description = descriptions[i];
geocoder.geocode(
{
'address': address,
'region' : 'uk'
},
function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
markersArray[i] = marker;
console.log(markersArray[i]);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(description);
infowindow.open(map, marker);
}
})(marker, i));
} else {
alert("Geocode was not successful for the following reason: " + status);
return false;
}
}
);
var bounds = new google.maps.LatLngBounds();
$.each(markersArray, function (index, marker) {
bounds.extend(marker.position);
});
map.fitBounds(bounds);
console.log(bounds);
}
Any thoughts? The issue seems to be with the value of the counter i inside the geocode function.
Any help much appreciated!
1) my info windows, which should take their text from another array,
always use the last array value
2) i can't get the map to center automatically. I'm using a bit of
code which has worked in other circumstances, but it doesn't in my
code.
1) Yes this is a closure issue. This is how I get around it.
I create an object to store all of the properties I will be using. In your example I am going to use the postcode and the description.
function location(postalcode, desc){
this.PostalCode = postalcode;
this.Description = desc;
}
Now do a quick loop to add all the location objects to an array.
var locations = [];
for(var i = 0; i < postcodes.length; i++) {
locations.push(new location(postcodes[i], descriptions[i]));
}
Extract the geocode functionality into its own function with a parameter to take a location object. Then you can loop through the location object array and geocode each individually. So now both the post code and description are in scope when the request is built and sent.
function GeoCode(singleLocation){
geocoder.geocode(
{
'address': singleLocation.PostalCode,
'region' : 'uk'
},
function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
//quick and dirty way
bounds.extend(marker.position);
map.fitBounds(bounds);
markersArray[i] = marker;
console.log(markersArray[i]);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(singleLocation.Description);
infowindow.open(map, this); //this refers to the marker
});
} else {
alert("Geocode was not successful for the following reason: "
+ status);
return false;
}
}
);
}
2) As you can see above the quick an dirty way to do this is extend and fit the bounds inside of the callback function for the geocode. This causes the fitBounds function to be called multiple times and isnt really a big deal if you only have a few markers, but will cause problems if you have hundreds or thousands of markers. In that case the right-way to do this is to create an async loop function. You can see an example of it on one of my previous answers.
Here is a functioning example of the code based on your example.
Two problems:
1) my info windows, which should take their text from another array,
always use the last array value
2) i can't get the map to center automatically. I'm using a bit of
code which has worked in other circumstances, but it doesn't in my
code.
Answers:
1) This is because most likely you have a closure issue here.
2) center will define the center point of your map, but in your code you have commented this
//center: new google.maps.LatLng(-33.92, 151.25),
removing the comment for this line will center to map to latitude of -33.92 and longitude of 151.25.
Use below:
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
Would someone tell me how to center on a country by name on the Google Maps API v3? I know how to do it in v2, but need to do it in v3.
You could use Geocoding to lookup the Lat/Lng of the country. Take a look at this sample from Google.
Basically you need to do something like this:
var country = "Germany";
var geocoder;
geocoder.geocode( {'address' : country}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
}
});
In your initialize function you'll need to set the value of the geocoder object, like this:
geocoder = new google.maps.Geocoder();
You'd need to workout what an appropriate zoom level would be, and then set that after you have centered the map.
This code working for me:
let geocoder = new google.maps.Geocoder();
let 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);
}
});
The only way I know how to do it would be by having a list of the countries and their respective Lat and Lng, with that information known you could use the following code.
var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
Out of curiosity, how would you do it in v2?