Google Fusion API and issues with displaying all the data - javascript

What I am trying to do is display vineyards in Colorado. It displays the custom icons and they are in the correct places; however, it does not display all the data. Only 11 points are being showed when there is over 50 of them. Is there anyway around this?
Edit: Here is also my Google Fusion table. Perhaps my formatting is wrong? https://www.google.com/fusiontables/DataSource?docid=1pYFq7mJ1uT4YYZ3LLzY4l7X8njLmZszJt05lucY#rows:id=1
Compare the Fusion map to this: http://s5.postimg.org/f80q3qhpz/display.png
Here is my HTML and Javascript.
<!DOCTYPE html>
<!--
-->
<html>
<head>
<title>Vineyards in Colorado</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<!-- Style -->
<style type="text/css">
body { height: 100%; margin: 0px; padding: 10px; }
#map_canvas { height: 600px; width: 700px; }
</style>
<!-- Google Maps API javascript -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<!-- Import the visualization javascript -->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<!-- Initialize visualization -->
<script type="text/javascript">
google.load('visualization', '1', {});
</script>
<script type="text/javascript">
var tableid = 1; //the table id
var map;
/* INITIALIZE - initialize the map and geocoder */
function initialize() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(39,-105.547222), //the center lat and long
zoom: 7, //zoom
mapTypeId: google.maps.MapTypeId.ROADMAP //the map style
});
//make gviz request
setData();
}
/* GVIZ - get data from Fusion Tables */
function setData() {
//create a viz query to send to Fusion Tables
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + encodeURIComponent("SELECT name, address FROM 1pYFq7mJ1uT4YYZ3LLzY4l7X8njLmZszJt05lucY"));
//set the callback function that will be called when the query returns
query.send(getData);
}
//define callback function, this is called when the results are returned
function getData(response) {
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
//create an array of row values
for (i = 0; i < numRows; i++) {
var row = [];
for (j = 0; j < numCols; j++) {
row.push(response.getDataTable().getValue(i, j));
}
codeAddress(row);
}
}
/* GEOCODING - geocode data in Fusion Tables, if the data is a String Address */
var geocoder;
var lastWindow;
//geocode the address, and create a new marker and InfoWindow at the geocoded location
function codeAddress(row) {
geocoder.geocode( { 'address': row[1] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var coordinate = results[0].geometry.location;
//create the marker
var marker = new google.maps.Marker({
map: map,
position: coordinate,
//this is where the magic happens!
icon: new google.maps.MarkerImage("http://s5.postimg.org/icgrcg88j/vineyard_2.png")
});
//add a click listener to the marker to open an InfoWindow,
google.maps.event.addListener(marker, 'click', function(event) {
if(lastWindow) lastWindow.close(); //close the last window if it exists
lastWindow = new google.maps.InfoWindow( {
position: coordinate,
content: row[0] //this is the row data, you can use HTML here for the content
});
lastWindow.open(map);
});
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>

You are geocoding the addresses, that will run into OVER_QUERY_LIMIT errors (at about 10 or so):
Add an else like this to see them:
if (status == google.maps.GeocoderStatus.OK) {
// .. your code
} else {
alert("geocode failed:"+status);
}
You have the latitude and longitude in the table, use them to display the marker, don't use the geocoder.
your data with FusionTableLayer

Related

Google Maps - Drawing the route without the markers

I am drawing a route for two points using Google Maps API but I have some inconvenient from this drawing. When I draw the route, Google it shows me on map two points, A and B, the origin and destination point.
The problem is that I can't take it out. I need to show only the route without this markers.
Have someone known how to show only the route?
The code is based on example from developers guide
https://plnkr.co/edit/UWfKc7XGHtdbeRZkUS8X?p=preview
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Directions service (complex)</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var startLatLng;
var endLatLng;
var startAddr = 'Grand Central Station';
var endAddr = 'City Hall';
function initMap() {
// Create a map and center it on Manhattan.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {lat: 40.771, lng: -73.974}
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
calculateAndDisplayRoute(directionsDisplay, directionsService);
}
function calculateAndDisplayRoute(directionsDisplay, directionsService) {
// Retrieve the start and end locations and create a DirectionsRequest using DRIVING directions.
directionsService.route({
origin: startAddr,
destination: endAddr,
travelMode: 'DRIVING'
}, function(response, status) {
// Route the directions and pass the response to a function to create markers for each step.
if (status === 'OK') {
directionsDisplay.setDirections(response);
console.log(response);
} else {
console.log('Directions request failed due to ' + status);
}
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCgkOZvjHinGyRsQT7WO1R7KGmtxJJfDPE&callback=initMap">
</script>
</body>
</html>
I found the solution:
directionsDisplay.setOptions({suppressMarkers: true});
And here the link to the documentation where all the options are explained

Uncaught error: google is not defined for Google Map API geocoder

Hey Im currently using the Google API to render a map onto my application; however, I am running into a problem where Im using the Google's Geocoding library but it is running into an uncaught error: google is not defined.
I dont understand this error, because I use it to render the map itself, and the google object is being read and rendering the map fine.
Here is my html scripts:
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script type="text/javascript" src="js/scripts.js" async></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap" async defer>
</script>
And here is my javascript file:
function initMap() {
var geocoder = new google.maps.Geocoder(),
fromLatLng = getLatLng(geocoder, "Pasadena, California"),
startLatLng = getLatLng(geocoder,"Los Angeles, California"),
fromLocation = new google.maps.LatLng(fromLatLng),
destLocation = new google.maps.LatLng(startLatLng),
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 32.8615616, lng: -117.2188185}, // TODO change to start location
zoom: 7 // continet level
}),
directionService = new google.maps.DirectionsService(),
directionRender = new google.maps.DirectionsRenderer({
map: map
}),
markerA = new google.maps.Marker({
position: fromLocation,
title: "Point A",
label: "A",
map:map
}),
markerB = new google.maps.Marker({
position: destLocation,
title: "Point B",
label:"B",
map:map
});
console.log(fromLocation)
renderRoute(directionService, directionRender, fromLocation, destLocation);
} // end of initMap
function getLatLng(geocoder, address) {
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
if(results[0].geometry.location){
console.log("Successfully Lat/Lng converted");
return results[0].geometry.location;
}
else{
console.log("Couldn't properly convert");
}
} else {
console.log('Geocode was not successful for the following reason: ' + status);
}
});
}
I've tried changing around the scripts and a lot of other stackoverflow posts but havent found any luck.
Your geocode use wasn't right.
I have to admit that it was a tricky one!
I never used that service before... I even had to enable it!!
What I found out is that it has a delay to retreive the info.
Yeah... It's a get request after all...
And you do it twice.
So what I did is to set an interval to check if both 2 Geocode resquests callback had executed before setting the map, since needed to set the markers.
I implemented it in a new function which I called doGeocode().
This is also your map API callback in the script call, instead of initMap.
This function, after getting the 2 geocodes latitude/longitude, finally calls the initMap() to render your desired result.
The only thing I couldn't find out is your renderRoute function... Since not provided in your question. But I think you will be able to handle it.
So... Have a look at the result on my server here.
The full code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>SO # 39909383</title>
<link rel="icon" type="image/gif" href="https://www.bessetteweb.com/cube-fallback/images/sept.gif">
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<!-- Google Maps CSS-->
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Open+Sans:300">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
cursor: pointer !important;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
var fromLocation;
var destLocation;
var callbackCounter=0;
function initMap() {
console.log("Map initialisation");
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 32.8615616, lng: -117.2188185}, // TODO change to start location
zoom: 7, // continent level
mapTypeId: google.maps.MapTypeId.SATELLITE // TERRAIN, HYBRYD, ROADMAP
});
var directionService = new google.maps.DirectionsService();
var directionRender = new google.maps.DirectionsRenderer({
map: map
});
var markerA = new google.maps.Marker({
position: fromLocation,
title: "Point A",
label: "A",
map:map
});
var markerB = new google.maps.Marker({
position: destLocation,
title: "Point B",
label:"B",
map:map
});
// renderRoute == not a function!!
// Missing in the question...
// Temporarly commented out.
//
//renderRoute(directionService, directionRender, fromLocation, destLocation);
} // end of initMap
function getLatLng(geocoder, address) {
geocoder.geocode({'address': address}, function(results, status) {
console.log("callbackCounter: "+callbackCounter);
if (status === 'OK') {
if(results[0].geometry.location){
console.log("Successfully Lat/Lng converted");
// Only to see clearly in console.log()
var latlong = JSON.stringify(results[0].geometry.location);
console.log( latlong );
latlong = JSON.parse(latlong);
callbackCounter++;
// Set from
if(callbackCounter==1){
fromLocation = latlong;
}
// Set dest
if(callbackCounter==2){
destLocation = latlong;
}
// Function end.
return;
}
else{
console.log("Couldn't properly convert");
}
} else {
console.log('Geocode was not successful for the following reason: ' + status);
}
});
}
function doGeocode(){
var geocoder = new google.maps.Geocoder();
getLatLng(geocoder, "Pasadena, California");
getLatLng(geocoder,"Los Angeles, California");
// Wait for from and dest locations found ( Geocoder get delay )
var waitForCoords = setInterval(function(){
console.log("--- Interval");
if(callbackCounter==2){
clearInterval(waitForCoords);
console.log("--- Interval cleared");
// Ready to initialise the map!
initMap();
}
},50);
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]&callback=doGeocode"></script>
</body>
</html>

Multiple Google Maps icons?

I'm trying to combine the following two blocks of codes together.
but for some reason, when i load the page in the browser, First the second blocks of code loads the marker on the map and then the page refreshes and the first blocks of code loads on the map!
This is my entire code:
<!DOCTYPE html>
<html>
<head>
<title>Google maps</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
geocoder = new google.maps.Geocoder();
function initialize() {
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
codeAddress();
}
function codeAddress() {
var address = '<?= $_GET['location'] ?>';
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({
icon: 'meicon.png',
map: map,
position: results[0].geometry.location
});
} else {
alert("Error loading map");
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<script type="text/javascript">
var locations = [
['Bondi Beach', 51.5033631,-0.1276253, 1]
];
var maps = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 15,
center: new google.maps.LatLng(51.5033630,-0.1276250),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var markers, i;
for (i = 0; i < locations.length; i++) {
markers = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: maps
});
google.maps.event.addListener(markers, 'click', (function(markers, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, markers);
}
})(markers, i));
}
</script>
</body>
</html>
could someone please advise on this issue?
Thanks in advance.
It's probably because you're calling the geocoder on the address in the first block, which is an async call to google to check the address. While the code is talking to google the page runs the second code block. When that call returns it runs the rest of the code in the first block, which sets the center of the map.
The reason is simple you are loading two map the first called in <head> script what build a map in map-canvas named map. the second in body script you create another map named maps and this too create in map-canvas.You need only a working map and with this do what you nedd.

Retrieve marker position to fields to submit

I have this code from the Google API docs. It does exactly what I want except i need to be able to get to get latitude and longitude of the marker once its been placed.
In my site , i have enabled the option to be able to select a location on the map, but i need to somehow get the latitude and longitude information from the marker that the customer has set, specifically in hidden fields so that i could store them when data is posted $_POST.
The code I have now is:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=jsdlkajslkdjaslkdja&sensor=false&language=ar&region=SAU">
</script>
<script type="text/javascript">
var map;
var markersArray = [];
function initialize() {
var haightAshbury = new google.maps.LatLng(26.1631, 50.2044188);
var mapOptions = {
zoom: 7,
center: haightAshbury,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
}
function addMarker(location) {
marker = new google.maps.Marker({
position: location,
map: map
});
markersArray.push(marker);
}
// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
}
// Shows any overlays currently in the array
function showOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(map);
}
}
}
// Deletes all markers in the array by removing references to them
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
I mainly need help on the JS side of this.
There is a markersArray-variable which contains all markers.
Loop over the array, you will get the lat/lng for each item by using
item.getPosition().lat() and item.getPosition().lng()
<edit>
Limiting to 1 marker is easy.
Change this line:
google.maps.event.addListener(map, 'click', function(event) {
into this:
google.maps.event.addListenerOnce(map, 'click', function(event) {
</edit>

Fetching nearby locations from google places and adding markers on google map from results

EDIT: SOLVED. Correct code below the problem code.
I'm having trouble getting my code to work. What I want to do is to use geolocation to determine the users location. I then want to do a search to locate something from a string (in this case, "Systembolaget", in a radius of 2000, and show the results on a google map. I get my own location on the map, but i'm having big trouble getting the places results.
What am I doing wrong? I don't have that much experience from javascript, so all help is good help.
If you're wondering about the cordova script, it's necessary since I'm doing a phonegap application.
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script src="cordova-1.6.0.js"></script>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=MYAPIKEY&sensor=true"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script type="text/javascript">
// Determine support for Geolocation and get location or give error
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayPosition, errorFunction);
} else {
alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}
// Success callback function
function displayPosition(pos) {
var mylat = pos.coords.latitude;
var mylong = pos.coords.longitude;
//Load Google Map
var latlng = new google.maps.LatLng(mylat, mylong);
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Places
var request = {
location: latlng,
radius: '2000',
name: ['Systembolaget']
};
var service = new google.maps.places.PlacesService(map);
service.search( 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];
var loc = place.geometry.location;
var marker = new google.maps.Marker
({
position: new google.maps.LatLng(loc.Pa,loc.Qa)
});
marker.setMap(map);
}
}
}
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"You are here"
});
}
// Error callback function
function errorFunction(pos) {
alert('It seems like your browser or phone has blocked our access to viewing your location. Please enable this before trying again.');
}
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
SOLVED! CORRECT CODE!
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
<title name="title"></title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="cordova-1.6.0.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script type="text/javascript">
// Determine support for Geolocation and get location or give error
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayPosition, errorFunction);
} else {
alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}
// Success callback function
function displayPosition(pos) {
var mylat = pos.coords.latitude;
var mylong = pos.coords.longitude;
//Load Google Map
var latlng = new google.maps.LatLng(mylat, mylong);
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Places
var request = {
location: latlng,
radius: '20000',
name: ['whatever']
};
var service = new google.maps.places.PlacesService(map);
service.search( 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]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
}
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"You're here"
});
}
// Error callback function
function errorFunction(pos) {
alert('It seems like your browser or phone has blocked our access to viewing your location. Please enable this before trying again.');
}
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
It's hard to give you specific help, because you haven't really described exactly how you are failing. But one thing I notice right away is that you appear to be trying to load the google.maps script twice, with different sensor information in each. In your first google.maps script tag you include the literal text MYAPIKEY which is has to be incorrect. If you had a real key in a variable, I would expect something like:
src="http://maps.googleapis.com/maps/api/js?key=" + MYAPIKEY + "&sensor=true"
And then in your second script tag you appear to load the places library correctly, but then your sensor tag is set as: sensor-false. Your 2nd script tag appears more correct to me, so I would suggest removing the first script tag as a start.
From there, can you provide more detail about how your page is failing and maybe a link to the page?
Some additional observations:
Your initial if-else looks as if it will call the displayPosition function, but the code within displayPosition will not load the google map; it simply creates some vars that then go out of scope when the function ends.
Outside of the displayPosition function, you create a new instance of the google Map, but it references myOptions, which no longer exists at this point in the code, because it only existed within the scope of the displayPosition function.
I would suggest changing the code related to Map creation to something like:
var map = null;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayPosition, errorFunction);
} else {
alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}
// Success callback function
function displayPosition(pos) {
var mylat = pos.coords.latitude;
var mylong = pos.coords.longitude;
//Load Google Map
var latlng = new google.maps.LatLng(mylat, mylong);
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

Categories

Resources