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.
Related
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)
fairly new to javascript and trying to make a simple map application. I am trying to center a new map around an address that is passed through a function. The issue I have is it is always being returned null which I do not understand, do I have to specify return types in the function format?
My code:
<script>
var geocoder;
var map;
function initialize() {
var address = document.getElementById('address').value;
var latlng = GetLatLong(address);
alert(latlng);
var mapOptions = {
zoom: 8,
center: latlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function GetLatLong(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert(results[0].geometry.location)
return results[0].geometry.location;
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I have a div for the address text and a div for the map location. To debug I put alert("") in some places to see the order in which it gets called on runtime, why would the line I put the first alert be called before the function is called?
Thanks
The Google Maps API call that you are performing is asynchronous. In layman's terms that means that as soon as you start the call, the rest of your program keeps executing independent of it. It is essentially running to the side of the rest of your program. The purpose of the function that you pass to the geocoder call is to deal with the data that the call returns asynchronously.
You would need to change your code to do something like this:
function initialize() {
var address = document.getElementById('address').value;
GetLatLong(address);
}
var map;
function GetLatLong(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert(results[0].geometry.location)
var latlng = results[0].geometry.location;
var mapOptions = {
zoom: 8,
center: latlng
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
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.
in my Asp.net Web Application where i am using the setTimeout to Get rid of
geocoder OVER_QUERY_LIMIT, the shorter time out is 10ms which is too longer for me, I have 800 above addresses coming from SQL SERVER which would be increased because of this setTimeout will take about 5 to 7 mints to take places of all the markers on map and that`s frustrating. I researched and saw this link setTimeout: how to get the shortest delay
but cant figure out what he want to do actually. please someone guide me....
function InitializeMap() {
// Here am calling the webService by PageMethods in which CityNames, Countries Name will take their places
PageMethods.GetCitiesbyUser_Extender(onSucess);
var myOptions =
{
zoom: 0,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
// Creating latlngbound to bound the markers on map
var bounds = new google.maps.LatLngBounds();
//// Creating an array that will contain the addresses
var places = [];
// Creating a variable that will hold the InfoWindow object
var infowindow;
// create this to add the marker Cluster on map
mc = new MarkerClusterer(map);
var popup_content = [];
var geocoder = new google.maps.Geocoder();
// image for ballon i want to change default ballon to this
var iconimage = "http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=FFFFFF,008CFF,000000&ext=.png";
var markers = [];
// Create this function for passing the values which was taken by webservice cntName is the return in webservice
function onSucess(cntName){
// loop through the cntName to pass the individual City one by one from geocode
for (i = 0; i < cntName.length; ++i) {
//for fixing the issue use closure to localize the cntName[i] variable before passing into geocode and callback function within it.
(function CreateMarkAndInfo(address) {
geocoder.geocode({ 'address': address },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
places[i] = results[0].geometry.location;
var marker = new google.maps.Marker({
position: places[i],
title: results[0].formatted_address,
map: map,
icon: iconimage
});
markers.push(marker);
mc.addMarker(marker);
google.maps.event.addListener(marker, 'click', function () {
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
// Setting the content of the InfoWindow afterward
infowindow.setContent(popup_content[i]);
// Tying the InfoWindow to the marker afterward
infowindow.open(map, marker);
});
// Extending the bounds object with each LatLng
bounds.extend(places[i]);
// Adjusting the map to new bounding box
map.fitBounds(bounds);
// Zoom out after fitBound
var listener = google.maps.event.addListenerOnce(map, "idle", function () {
if (map.getZoom() < 10) map.setZoom(2);
});
}
else {
// if geocode will end the limit then make delay by timer in order to avoid the OVER_QUERY_LIMIT
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function () { CreateMarkAndInfo(address); }, (15)); // here i think i should use better approch but for now it`s ok.
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
}
});
})(cntName[i]);// End closure trick
}
}
}
google.maps.event.addDomListener(window, 'load', InitializeMap);
Edit:
#just.another.programmer i cant because there is no latitute and longitude in DB, client will add cities and countries by him self thats why i had to convet city and country names by geocode and geocode doing it`s job accuretly here
How i am calling the City and country Names by web service
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod()]
public static string[] GetCitiesbyUser_Extender()
{
System.Data.DataSet dtst = new System.Data.DataSet();
string ses = HttpContext.Current.Session["UserName"].ToString();
USTER.Dal.clsSearch clssearch = new USTER.Dal.clsSearch();
// Assinging the Stroed Procedure Method to DataSet
dtst = clssearch.GetAllCitiesByUser(ses);
string[] cntName = new string[dtst.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (System.Data.DataRow rdr in dtst.Tables[0].Rows)
{
// Columns Name in SQL Server Table "CityName" and "CountryName"
cntName.SetValue(rdr["CityName"].ToString() +","+ rdr["CountryName"].ToString() , i);
i++;
}
}
catch { }
finally
{
}
return cntName;
}
Geocode your addresses one time when you first get them, then store the lat/long in your db so you don't have to geocode again. This will dramatically reduce your geocode requests and remove the need for setTimeout.
First off thank you in advance for taking time to help me with this, I appreciate your efforts.
I have a problem with google maps api, JavaScript version 3.
I have written the following code
$('.adr').ready(function(){
initialize();
})
function initialize() {
var myLatlng = codeAddress();
var myOptions = {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
}
function codeAddress()
{
var geocoder = new google.maps.Geocoder();
var address;
var street = cropAdr($(".street-address").text());
var city = cropAdr($(".locality").text());
var state = cropAdr($(".region").text());
var zip = cropAdr($(".zip").text());
address = street + ", " + city + ", " + state + ", " + zip;
geocoder.geocode( {'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var latlng = results[0].geometry.location;
return latlng;
}
else
{
alert("Geocode was not successful for the following reason: " + status);
return null;
}
});
}
function cropAdr(args)
{
var index = args.indexOf(":");
var value = args.substr(index+1);
return value;
}
But it doesn't work.
I have checked the value of the "results[0].geometry.location" return and its perfect, so the address manipulation works. The "results[0].geometry.location" is a google.maps.Latlng object, but I have tried to strip out just the co-ords as strings, then create a new google.maps.Latlng object but no dice.
yet if I manually copy that string and paste the value into "var myLatlng = new google.maps.Latlng(Paste Copied String here!)" the whole thing works!!
I cannot see what else is wrong this script (apologies for the jumble of Jquery and Javascritpt).
The Google Maps API Geocoder accepts a function that will be run when the address has been geocoded, but that function may be called asynchronously - that is, after the rest of your code has already finished running.
In codeAddress you call the Geocoder and pass in a function with this line:
geocoder.geocode( {'address': address}, function(results, status)
You then try and return a latLng from the function passed to the geocoder, but that is not the same as returning a value from codeAddress. The value you return from inside this function will be passed to the geocoder object, which will just ignore it.
You need to have the function you pass to geocode do something with the latLng. For example, replace:
return latLng;
with:
map.setCenter(latLng);
And the map should center itself on the geocoded address once the result is available.
(To do this you will need to make the map object global or otherwise make it available to codeAddress. I suggest adding "var map;" at the top of your code, and remove "var" from in front of the use of map in initialize)