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.
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)
I have been sifting through documentation unsuccessfully and need help. I need to access the first value in Google places autocomplete or geocode the lat lng coords I have in Google Places. I am auto populating the field with say "Palo Alto" and need Google Places' first suggestion for an auto complete of that city. I have tried using the Google Geocode feature but the results are different than the Places API and therefore useless to me. Example places outputs Palo Alto, CA and the geocode feature outputs Palo Alto, CA USA. I have tried hacking it together by reverse geocoding the lat lng splitting the string above to only say Palo Alto and populating an input field that is hooked into a Places autocomplete, but I can't get it to trigger. I have a script written to pull the output from the autocomplete results; I just need to trigger it. I have tried using $('myCity').trigger('keypress'); once I have inserted Palo Alto into the input field to no avail. All suggestions on what steps to take next are welcome. I have also looked into the following code, but I want to do it without the map and i get a javascript error when i remove it. "TypeError: a is undefined [Break On This Error] (66 out of range 46)"
var lat = -130;
var lng = 37;
var request = {
location: new google.maps.LatLng(lat, lng);
};
var service = new google.maps.places.PlacesService(map);
service.search(request, function (results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
console.log(results[i])
}
}
});
Thanks for your help.
You need to perform a Text Search.
Go to Places Library and go down to Text Search Requests.
Heres an example:
var map;
var service;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: '500',
query: 'restaurant'
};
service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
Note: In your case change the request to this:
var request = {
query: 'Palo Alto'
};
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
});
So I've got this script where I'm trying to add markers to a map I've created with Javascript. I think I'm pretty near to getting it right (yeah, right) but I'm not sure what I'm doing wrong and I can't seem to decipher the error I'm getting.
The first thing I do is add the google API key to my site.
Then, the first thing I do in my script is load the search and maps APIs:
(function ($) {
$("document").ready(function() {
google.load("maps", 2, {"callback": mapsLoaded});
});
})(jQuery);
After the 'maps' API has loaded, the mapsLoaded method gets called:
function mapsLoaded() {
//Create the options for the map and imediately after create the map.
var myOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("result_map"), myOptions);
showUserLocation(map);
var image = '../misc/planbMarker.png';
var postcodes = document.getElementsByClassName('result-postcode');
var geocoder = new google.maps.Geocoder();
for(var i = 0; i < postcodes.length; i++) {
var address = postcodes[i].value;
geocoder.geocode({'address': address}, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[i].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
The function showUserLocation just gets the user's current location and puts it in the map:
function showUserLocation(map) {
//Define the user's initial location
var initialLocation;
//Define the variable to see if geolocation is supported.
var browserSupportFlag = new Boolean();
// Try W3C Geolocation (Preferred)
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
// Browser doesn't support Geolocation
} else {
browserSupportFlag = false;
handleNoGeolocation(browserSupportFlag);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag == true) {
alert("Geolocation service failed. Defaulting to Aberdeen.");
initialLocation = new google.maps.LatLng(57.149953,-2.104053);
} else {
alert("Your browser doesn't support geolocation. We've placed you in Aberdeen.");
initialLocation = new google.maps.LatLng(57.149953,-2.104053);
}
map.setCenter(initialLocation);
}
//Put a marker on the user's current position different than the markers for the venues.
navigator.geolocation.getCurrentPosition(function(position) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
map: map,
title:"Hello World!"});
});
}
Now, the error I'm getting when I run this is: Uncaught TypeError: Cannot call method 'appendChild' of null at maps:1 followed by: Uncaught TypeError: Object #<Object> has no method '__gjsload__' and after about 5 seconds this also pops up in the javascript console:
Error in event handler for 'undefined': TypeError: Cannot call method 'postMessage' of null
at chrome/RendererExtensionBindings:100:18
at chrome-extension://bmagokdooijbeehmkpknfglimnifench/contentScript.js:128:13
at [object Object].dispatch (chrome/EventBindings:182:28)
at chrome/RendererExtensionBindings:99:24
at [object Object].dispatch (chrome/EventBindings:182:28)
at Object.<anonymous> (chrome/RendererExtensionBindings:149:22)
On a sidenote, and as another possibly symptom, when this error is happening Chrome is displaying a blank page (if you go to view source the markup is all there but the page is blank). I'm running Drupal 7.10.
Does anyone have any ideas on what I'm doing wrong?
Firstly, Google Maps API 3 doesn't require an API key (unless we're referring to the recently introduced key for sites with over 25,000 daily map views which might need to pay for usage). It sounds like you're mixing up the keys required for API 2 with code for API 3.
Secondly, this is all wrong. 'i' is a variable for the postcodes array, it has no relationship to the results array
for(var i = 0; i < postcodes.length; i++) {
var address = postcodes[i].value;
geocoder.geocode({'address': address}, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[i].geometry.location
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)