I use the Google Maps API to save a database of addresses in a point.
Came across a problem which is the third day I can not decide. Can you give me some advise.
I cycle runs through all the points, which are marked on the map, in which using geotsoder.geoŃode recognize and and use ajax write this address in the database.
Example:
function saveAddress(marker_points)
{
var i = 0;
id = 0;
address = [];
var count = 0;
points = [];
for(i in marker_points)
{
var geocoder = new google.maps.Geocoder();
geocoder.geocode( {'address': marker_points[i]},function(results, status){
address = results[0].formatted_address;
});
$.ajax({
type: "POST",
url: "/user.view.location.phone_id-{/literal}{$iPhoneId}{literal}.html",
cache: false,
data: "address=" + address + "&location_point=" + marker_points[i],
dataType: "html",
async: false,
timeout: 5000,
success: function (data) {
}
});
}
}
But in Ajax passed last point, ie written in the database returned last address and the last point on which this address.
Could you tell me what could be the problem and how to solve it, because he had tried all the options, it does not work?
You can use function closure to associate the request with the response.
Example using geocoded addresses:
They function that gets closure on "i" is:
function geocodeAddress(i) {
geocoder.geocode({'address' : locations[i]},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
createMarker(results[0].geometry.location, i);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
I think your script may sometimes call ajax method before getting response from geocoder.geocode. Try to put $.ajax method inside of
function(results, status){
address = results[0].formatted_address;
}
so that fragment of your code would look something like:
var marker_points = ["50.463425,30.508120","50.465822,30.514380","50.465317,30.515609"];
for(i in marker_points) {
codeAndSendAddress(marker_points[i]);
}
function codeAndSendAddress(point){
var mp = point.split(',');//Extract numbes from string
var latLng = new google.maps.LatLng(mp[0],mp[1]) // create latitude/logitude object
geocoder.geocode( { 'latLng': latLng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) { make sure location was found
var geocodedAddress = results[0].formatted_address;
var geocodedLocationPoint = results[0].geometry.location;
$.ajax({
type: "POST",
url: "/user.view.location.phone_id-{/literal}{$iPhoneId}{literal}.html",
data: 'address='+geocodedAddress+
'&geocoded_location_point='+geocodedLocationPoint+
'&location_point='+point,
timeout: 5000,
success: function (data) {}
});
}
});
}
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I've got this code:
var get_lat = function(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log('lat is: '+ results[0].geometry.location.lat());
return results[0].geometry.location.lat();
}
});
}
var get_lng = function(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log('lng is: '+ results[0].geometry.location.lng());
return results[0].geometry.location.lng();
}
});
}
In console it prints the coordinates I need, but the return value is always undefined:
I use it in classic initialize for Google Maps like this:
function createMarker(latlng) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
});
}
function initialize() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(49.210366,15.989588)
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var address = "Correct address that console.logs the correct GPS coordinations in function definitions above";
var gps_lat = get_lat(address);
var gps_lng = get_lng(address);
console.log('GPS lat: ' + gps_lat); // logs "undefined"
console.log('GPS lng: ' + gps_lng); // logs "undefined"
var marker = createMarker({lat: gps_lat}, lng: gps_lng});
}
$(window).on("load", function (e) {
initialize();
});
Do you have any idea why the function consoles the right value but it doesn't return anything?
For GMAP API I use this script: http://maps.google.com/maps/api/js?sensor=false&libraries=geometry
You have the return inside an anonymous function that you pass to geocoder.geocode, all in yet another function (get_lat/get_lng). get_lat/get_lng themselves don't have a return statement, and thus return undefined.
Furthermore, geocoder.geocode will call your anonymous function asynchronously. Which means that there is no chance for get_lat/get_lng to get hold of the return value and return it where get_lat/get_lng was called.
One solution (the simplest one) is to put the createMarker code in the callback for geocoder.geocode. Also, in this case you will have to merge your two get_lat/get_lng functions. Example:
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var gps_lat = results[0].geometry.location.lat()
var gps_lng = results[0].geometry.location.lng();
console.log('lat is ' + gps_lat + '. lng is ' + gps_lng);
var marker = createMarker({lat: gps_lat, lng: gps_lng});
return results[0].geometry.location.lat();
}
});
You have to wait until Google API gives response. So write a logic to create marker in callback function of Google API as shown below.
var getLatLng = function (address)
{
geocoder.geocode({ 'address': address }, function (results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var location = results[0].geometry.location;
// Create marker once you get response from Google
createMarker({ lat: location.lat(), lng: location.lng() });
}
});
}
and call that function as shown below
function initialize()
{
var myOptions =
{
zoom: 8,
center: new google.maps.LatLng(49.210366, 15.989588)
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
var address = "Correct address that console.logs the correct GPS coordinations in function definitions above";
// Old code ------------------------------------------------
//var gps_lat = get_lat(address);
//var gps_lng = get_lng(address);
//console.log('GPS lat: ' + gps_lat); // logs "undefined"
//console.log('GPS lng: ' + gps_lng); // logs "undefined"
//var marker = createMarker({ lat: gps_lat, lng: gps_lng });
// ----------------------------------------------------------
// New code
getLatLng(address);
}
and you will get marker on a map
I have using knockout javascrit for the Google Map but i cant clear markers on the map, i have got error message there, error following
> Ripple :: Environment Warming Up (Tea. Earl Gray. Hot.) ripple.js:37
> web :: Initialization Finished (Make it so.) ripple.js:37 Uncaught
> TypeError: Object [object Object] has no method 'dxmap' Shops.js:70
> eula response: true ripple.js:47 Uncaught TypeError: Object [object
> Object] has no method 'dxmap' Shops.js:70 Uncaught TypeError: Object
> #<Object> has no method 'setMap' Shops.js:137
My code below could you please help me
function FetchNearestShops(latitud,longitud)
{
$.ajax({
type: 'POST',
async:false,
contentType: 'application/json',
dataType: 'jsonp',
url: url + "/GetNearestShop",
//data: { Latitude: 9.998472, Longitude: 76.308059 },
data: { Latitude: latitud, Longitude: longitud },
success: function (data) {
loc.removeAll();
productsNear.removeAll();
$.map(data, function (item) {
loc.push({ label: item.ShopName, location: [item.Latitude, item.Longitude] });
//productsNear.push({ Name: item.ShopName, IsFavorite: false, Address: "", id: item.ShopId, Image: "mockcontent/shopimages/1.jpg" });
productsNear.push({ Name: item.ShopName, IsFavorite: item.Isfavourite, Address: item.Address, id: item.ShopId, Image: item.ImageUrl });
});
alert();
viewModel.options.markers = loc;
},
error: function () {
alert("error");
}
});
}
function SetLocation() {
var geocoder = new google.maps.Geocoder();
//var address = "ernakulam";
//alert(viewModel.options.location());
geocoder.geocode({ 'address': txtAddress() }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
ClearMap();
FetchNearestShops(latitude, longitude);
}
});
}
function ClearMap()
{
var markers = viewModel.options.markers();
for (var i = 0; i < markers.length; i++) {
markers[i];
markers.setMap(null);
}
markers;
}
I think you have problem in loop of your ClearMap() function. Try
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
Instead markers.setMap(null);.
Also i'm no sure what your markers it is correct collection of Google Markers.
This collection should look something like this:
markers[i] = new google.maps.Marker({
position: new google.maps.LatLng('some latitude', 'some longitude'),
map: map, //object of Google Map
name: 'Marker Name'
});
I have directions working on my custom map. However I was hoping to add the pulldown I found on Google's Developer site that allows choices like "Bicycle", "Driving", "Transit", "Walking".
Here is my code that calls function I know not where they are:
var map;
var gdir;
var geocoder = null;
var addressMarker;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
gdir = new GDirections(map, document.getElementById("directions"));
GEvent.addListener(gdir, "load", onGDirectionsLoad);
GEvent.addListener(gdir, "error", handleErrors);
setDirections(document.getElementById("fromAddress").value, document.getElementById("toAddress").value, "en_US");
}
}
function setDirections(fromAddress, toAddress, locale) {
gdir.load("from: " + fromAddress + " to: " + toAddress,
{ "locale": locale });
}
and here is the URL and what I think is what I need put somewhere in what I have.
--I figure I can test it with just one mode, like "WALKING", first. Then add the pulldown once it works.
=====================================
URL I found this at:
https://developers.google.com/maps/documentation/javascript/examples/directions-travel-modes
=========================================
function calcRoute() {
var selectedMode = document.getElementById('mode').value;
var request = {
origin: haight,
destination: oceanBeach,
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selectedMode]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
This is in the code above and I want to use it
travelMode: google.maps.TravelMode["WALKING"]
I figured it out. I'm trying to add v3 features/syntax to v2. Doh! (slaps forehead)
I have been trying to get the users location using the map v3 and show the path from there location to a fixed destination. But i had no luck finding a solution to get the users location, i have read the API but couldn't figure out anything checked all the examples still the same . hope some one can help me Thanx.
Solution:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
function initialize() {
var loc = {};
var geocoder = new google.maps.Geocoder();
if(google.loader.ClientLocation) {
loc.lat = google.loader.ClientLocation.latitude;
loc.lng = google.loader.ClientLocation.longitude;
var latlng = new google.maps.LatLng(loc.lat, loc.lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
alert(results[0]['formatted_address']);
};
});
}
}
google.load("maps", "3.x", {other_params: "sensor=false", callback:initialize});
google.loader.ClientLocation only gives a very approximate estimate as to the user's location.
Best choice is to use that as a fallback if HTML5 geolocation is not present, or not allowed by the user.
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(p) {
//get position from p.coords.latitude and p.coords.longitude
},
function() {
//denied or error
//use google.loader.ClientLocation
}
);
} else {
//use google.loader.ClientLocation
}
jQuery('#map_canvas').gmap({ 'zoom':2,'center':new google.maps.LatLng(39.809734,-98.55562), 'callback': function() {
var self = this;
self.getCurrentPosition(function(position, status) {
if ( status === 'OK' ) {
clientlat = position.coords.latitude;
clientlon = position.coords.longitude;
var clientlatlng = new google.maps.LatLng(clientlat, clientlon);
}
});
}});
What is making the following code get the country and not the city, and how can I change it to get the city instead of country?
function get_visitor_country() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lon);
geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var country = results[results.length-1].formatted_address;
$("#location-detection .location-name").html(country);
$("#geolocation-worked").css("display", "block");
$("#no-geolocation").css("display", "none");
$geolocation_fix.hide().css({ height : 0 });
init_geolocation_switch();
}
}
});
});
}
}
The script is also loading http://maps.google.com/maps/api/js?sensor=false at the end of the file, if that might be affecting it.
Your script currently is not getting anything special(like a city or a country) , it gets something out of the results.
To get the city search inside the results for an entry with types set to ["locality", "political"]
When you found it you got the city.
Creation of an object labeled with addressTypes for convenient access:
var components={};
jQuery.each(results,function(i,v){
components[jQuery.camelCase(v.types.join('-'))]=v;
})
//test it
alert((components.localityPolitical)
? components.localityPolitical.formatted_address
: 'n/a');
See: Address Component Types