Google Map API - Infowindow display google place API information - javascript

I am not sure how to go about this.
What I want:
I want to display the information that you might find if you were to go to https://www.google.com/maps and search for the farmers' market.
I want an Info window that provides the address, hours of operation, and possibly additional information that Google Maps provides for this business.
What I have now:
I have an Angular JS code block that populates an array that looks like the following:
var locations = [
['Findlay Market', 39.115398, -84.518481, 5],
['Hyde Park Farmers' Market', 39.139601, -84.442496, 4],
['Lettuce Eat Well Farmers' Market', 39.166134, -84.611613, 3],
['College Hill Farm Market', 39.195641, -84.545453, 2],
['Anderson Farmers' Market', 39.078364, -84.350539, 1]
];
Then I use the Infowindow to display the name of the farmers market.
I know that I could add a new table to my database for hours and additional information and use that to create an Angular JS card that I could display in the Infowindow... BUT I was hoping there would be a way to use the Google Map API with the Google Places API to get that information instead of storing it in my database.
Thanks to uksz I was able to use the below code to help me get the information I needed.
<!DOCTYPE html>
<html>
<head>
<title>Place details</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<script>
function initialize() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(39.115398, -84.518481),
zoom: 15
});
var request = {
location: map.getCenter(),
radius: '500',
query: 'Findlay Market'
};
var service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
place: {
placeId: results[1].place_id,
location: results[1].geometry.location
}
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function() {
var content = results[1].name + '<br>' +
results[1].formatted_address + '<br>' +
results[1].opening_hours + '<br>' +
results[1].place_id + '<br>';
infowindow.setContent(content);
infowindow.open(map, this);
});
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>

So I don't know if I understood your question correctly, but if you only want to display the information from Google Places API, you can use theirs getDetails() function. This will return an object. If you don't want to store the object, why not just deleting the object after each time the user for example switches the view? This way you will not store this information in your database, at least not permanently.
Have a good one!
Here is their full getDetails() manual:
https://developers.google.com/maps/documentation/javascript/places#place_details_requests

Related

Linking Google Script Variable to the Javascript in HTML

So I feel I'm almost there to the solution but I'm really in need of help here. What I'm trying to do is to create an array using .getValues() to get a range that contains four columns (Name, Address, Latitude, and Longitude). After that I want to return the variable back into a global variable and then call that variable from the HTML side. I tried linking the google script with the HTML and then calling the variable there but having quite a bit of trouble with that. Thank you guys for all of your help!
Below is the google script:
var id = 'Spreadsheet Key';
function doGet(e) {
var html = HtmlService.createTemplateFromFile('Sample');
return html.evaluate().setTitle('Directory Map');
}
function entries() {
var blop =
SpreadsheetApp.openById(id).getSheetByName('Sheet1').getRange('A1:D').getValues();
return blop;
}
This is the HTML in Google Script.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
<script>
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 39.8283, lng: -98.5795},
zoom: 5,
mapTypeId: 'roadmap',
gestureHandling: 'greedy'
});
var locations = [blop];
for (var i = 0; i < locations.length; i++) {
var sites = locations[i];
var myLatLng = new google.maps.LatLng(sites[2],sites[3]);
var sites = new google.maps.Marker({
position: myLatLng,
map: map,
title: sites[0],
});
};
}
</script>
<script> google.script.run.entries(); </script>
<script src="https://maps.googleapis.com/maps/api/js?key=MyAPIKey&libraries=places&callback=initAutocomplete"async defer></script>
<script src="https://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="SampleCode.gs"></script>
</body>
</html>
The starting point is:
<script> google.script.run.entries(); </script>
The above code runs when the page is loaded in the browser. You need a "success handler", and then the success handler can store the data somewhere. You could put the data into a window variable, or local browser storage.
<script>
window.storeSheetValues = function(theReturnedData) {
console.log('theReturnedData: ' + theReturnedData)
console.log('typeof theReturnedData: ' + typeof theReturnedData)
window.mySheetData = theReturnedData;//Put the data into a window variable
}
google.script.run
.withSuccessHandler(storeSheetValues)
.entries();
</script>
Check the data type of the return value coming back from the server. If it's a string, you may want to turn it back into an array.

Passing Variables by Reference in JavaScript

I am trying to display and center a map for the users current location. Everything works fine if I manually enter a hard coded latitude and longitude, but these needs to be dynamic as one user often changes location.
I suspect I am making a basic mistake, but my logic seems like it is correct to me. Please check my work and let me know what I am doing wrong? The line that is remarked out with Latitude and Longitude is the line I want to use instead of the previous line with the hard coded values.
<!DOCTYPE html>
<html>
<head>
<title>W123</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
</head>
<body>
<div id='printoutPanel'></div>
<div id='myMap' style='width: 100vw; height: 100vh;'></div>
<script type='text/javascript'>
function showlocation() {
navigator.geolocation.getCurrentPosition(getLocation);
}
function getLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
}
function loadMapScenario() {
var mapOptions = {
credentials: 'My API key code goes here',
center: new Microsoft.Maps.Location(39.1887643719098, -92.8261546188403),
//center: new Microsoft.Maps.Location(latitude, longitude),
mapTypeId: Microsoft.Maps.MapTypeId.road,
zoom: 8
};
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), mapOptions);
var urlTemplate = 'http://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q-{timestamp}/{zoom}/{x}/{y}.png';
var timestamps = ['900913-m50m', '900913-m45m', '900913-m40m', '900913-m35m', '900913-m30m', '900913-m25m', '900913-m20m', '900913-m15m', '900913-m10m', '900913-m05m', '900913'];
var tileSources = [];
for (var i = 0; i < timestamps.length; i++) {
var tileSource = new Microsoft.Maps.TileSource({
uriConstructor: urlTemplate.replace('{timestamp}', timestamps[i])
});
tileSources.push(tileSource);
}
var animatedLayer = new Microsoft.Maps.AnimatedTileLayer({ mercator: tileSources, frameRate: 500 });
map.layers.insert(animatedLayer);
}
</script>
<script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?branch=experimental&callback=loadMapScenario' async defer></script>
</body>
</html>
You want to pass in the latitude and longitude into your loadMapScenario function as seen below
function loadMapScenario(latitude,longitude) {
....your code here....
}
Change your callback in the bing map include to a new function like "mapUserLocation" then have mapUserLocation perform the following tasks
function mapUserLocation() {
// code here to get the latitude and longitude from users position
loadMapScenario(latitude,longitude);
}

Spring MVC - Adding multiple markers to Google Map from the database

I am trying to display multiple markers on a map from my database. I have looked at other examples and have Google's examples working on my server, but can't seem to get it working with database information.
Here's what I have so far:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
</head>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/project" user="root" password="root" />
<sql:query dataSource="${snapshot}" var="result">
SELECT * from House;
</sql:query>
<div id="map"></div>
<script type="text/javascript">
var markerLat, markerLong;
markerLat = [
<c:forEach var="s" items="${result.rows}">
<c:out value="${s.lat}"/>,
</c:forEach>;
markerLong = [
<c:forEach var="s" items="${result.rows}">
<c:out value="${s.lng}"/>,
</c:forEach>;
function initialize() {
var map;
var initlatlng = new google.maps.LatLng(markerLat[0],markerLong[0]);
var mapOptions = {
zoom: 6,
center: new google.maps.LatLng(36,5),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < markerLat.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(markerLat[i], markerLong[i]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(markers[i]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBiKZEYI58kG67y8dT50HG4ByxMmWHbwXA"
async defer></script>
It is giving me an error saying "Uncaught ReferenceError: google is not defined"
Could anyone tell me what I'm doing wrong or direct me to other examples of adding multiple markers to a map from a database?
This code is loading the Google Maps javascript API asynchronously:
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBiKZEYI58kG67y8dT50HG4ByxMmWHbwXA"
async defer></script>
You should either:
A. load the Google Maps Javascript API synchronously:
remove the "async defer" from the script include
load the Google Maps Javascript API prior to using the google.maps namespace.
B. load it asynchronously and use the callback parameter to execute the code that depends on it once it has loaded:
remove this line google.maps.event.addDomListener(window, 'load', initialize);
change the API include to:
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBiKZEYI58kG67y8dT50HG4ByxMmWHbwXA
&callback=initialize"
async defer></script>

Flickr API-Flickr geotagged photos not being displayed as map markers

My Geotagged photos in my Flickr map cannot be displayed in my google map.
I intend to display Flickr photos as info windows in my Google Map and using the URL wizard, I constructed an URL that calls the Flickr API, created and geotagged 7 photos which I want to display in my Google Map.
With geotagged locations each containing a map, once you load your map the markers are supposed to be displayed together with an info window displaying a photo in your Flickr a/c. Below is a sample code that is meant only to display markers of the geotagged photos is my Flickr map. Those are my APIkeys as well as user_ID. I think the problem is in the URL I constructed in the Flickr API explorer.
<!DOCTYPE html>
<html>
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Google and Flickr API mashup</title>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<!--Linking to the jQuery library.-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<!--Linking to the Google Maps API-->
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDo4wMMR44B6xsfGKVsB1MqQM8XlbBNdPo&sensor=true">
</script>
<script type="text/javascript">
var lat = 0;
var long = 0;
$(document).ready(function(){
//Connects to the Flickr API and reads the results of the query into a JSON array. This query uses the 'flickr.photos.search' method to access all the photos in a particular person's user account. It also uses arguments to read in the latitude and longitude of each picture. It passes the resultant JSON array to the 'displayImages' function below.
$.getJSON("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=09dba1a04e20620b4b95e701b08f9142&user_id=117523264#N05&has_geo=1&extras=geo&format=nojsoncallback", displayImages);
function displayImages(data){
//Loop through the results in the JSON array. The 'data.photos.photo' bit is what you are trying to 'get at'. i.e. this loop looks at each photo in turn.
$.each(data.photos.photo, function(i,item){
//Read in the lat and long of each photo and stores it in a variable.
lat = item.latitude;
long = item.longitude;
//Get the url for the image.
var photoURL = 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_m.jpg';
htmlString = '<img src="' + photoURL + '">';
var contentString = '<div id="content">' + htmlString + '</div>';
//Create a new info window using the Google Maps API
var infowindow = new google.maps.InfoWindow({
//Adds the content, which includes the html to display the image from Flickr, to the info window.
content: contentString
});
//Create a new marker position using the Google Maps API.
var myLatlngMarker = new google.maps.LatLng(lat,long);
//Create a new marker using the Google Maps API, and assigns the marker to the map created below.
var marker = new google.maps.Marker({
position: myLatlngMarker,
map: myMap,
title:"Photo"
});
//Uses the Google Maps API to add an event listener that triggers the info window to open if a marker is clicked.
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(myMap,marker);
});
});
}
});
</script>
</head>
<body>
<!--<p>Google maps and Flickr API mashup</p>-->
<p> </p>
<div id="map_canvas">
<script>
//Using the Google Maps API to create the map.
var myLatlngCenter = new google.maps.LatLng(-1.292066,36.821946);
var mapOptions = {
center: myLatlngCenter,
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var myMap = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
</script>
</div>
</body>
</html>
The original URL I constructed was http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=b6e73e16e28daf5d40f68947ce431d82&user_id=117523264%40N05&has_geo=1&extras=geo&format=json&nojsoncallback=1 and I did not sign call. Since I needed to push the results into a function, in our case the end should be nojsoncallback=?

Centering a google map with javascript from pin

I have my page so that it allows the user to see their latitude and longitude. I've embedded a google map so that the user can click physically see where they're at. This is a project for my computer science class, so I don't want you to physically write the code for me. I just want suggestions on how to solve this. Here's what I have right now.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<!-- This page will allow the suer to track their location through means of the HTML5 Geolocation feature -->
<title>Assignment 4:Track My Location</title>
<meta name="author" content="Alan Sylvestre" />
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function myLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(locationReveal);
} else {
alert("Please use a different browser that supports geolocation.");
}
}
window.onload = myLocation;
function locationReveal(position) {
showMap(position.coords);
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var div = document.getElementById("location");
div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
}
var map;
function showMap(coords) {
var googleLatAndLong = new google.maps.LatLng(coords.latitude, coords.longitude);
var mapOptions = {
zoom : 18,
center : googleLatAndLong,
mapTypeId : google.maps.MapTypeId.SATELLITE
};
var mapDiv = document.getElementById("map");
map = new google.maps.Map(mapDiv, mapOptions);
addMarker(googleLatAndLong);
}
google.maps.Map(mapDiv, mapOptions);
var marker;
function addMarker(latlong) {
var markerOptions = {
position : latlong,
map : map
};
marker = new google.maps.Marker(markerOptions);
}
var center;
function calculateCenter() {
center = map.getCenter();
}
</script>
</head>
<body style="background-color:yellow;" text="blue;">
<div align="center">
<h1>Reveal My Location</h1>
<p>
You know what's pretty cool? Tracking your location using a simple internet connection. By clicking this button, you're browser will track a global database and reveal your location in terms of latitude and longitude. Enjoy!
</p>
<div id="location"></div>
<br>
<div id="map" style="width:400px; height:400px;"></div>
<br>
<input type="button" id="centerOfMap" value="Center" onclick="calculateCenter()">
<footer>
<p>
© Copyright by Alan Sylvestre
</p>
</footer>
</div>
</body>
First you need to make sure that the DOM is loaded before you run your JavaScript.
That is why 'mapDiv' is 'undefined'.
Either wrap your script in a window.onload anonymous function or push it to just before the closing body tag.

Categories