I am new to javascript converting from VB. This is my first shot at creating a dynamic google map and am ultimatly trying to generate a google map using the users location and apply a places search for sports stores. Currently my map generates and zooms to my location but does not apply the search results with markers.
here is my code:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<article>
<p>Finding your location: <span id="status">checking...</span></p>
</article>
<script>
function success(position) {
var s = document.querySelector('#status');
if (s.className == 'success') {
// not sure why we're hitting this twice in FF, I think it's to do with a cached result coming back
return;
}
s.innerHTML = "found you!";
s.className = 'success';
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcanvas';
mapcanvas.style.height = '400px';
mapcanvas.style.width = '560px';
document.querySelector('article').appendChild(mapcanvas);
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeControl: false,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
var service;
var infowindow;
var request = {
location: latlng,
radius: '3200',
query: 'sports'
};
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]);
}
}
}
}
function error(msg) {
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
// console.log(arguments);
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
error('not supported');
}
</script>
I feel like I might be missing some var assignments or not over writing the current map from "map canvas". Has any one created something similar that provide some insight? Any help is greatly appreciated to find why my search results will not display on the map. Thanks!
Your code works but you are missing the createMarker function. This is not an API method.
Uncaught ReferenceError: createMarker is not defined
An example createMarker function:
function createMarker(place) {
new google.maps.Marker({
position: place.geometry.location,
map: map
});
}
Note: if you only need the location in that function you could also call it and modify it this way:
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
console.log(place);
createMarker(results[i].geometry.location); // pass only the location to createMarker
}
}
}
function createMarker(position) {
new google.maps.Marker({
position: position,
map: map
});
}
JSFiddle demo
Related
Input: user will select city and place category.
Output: google map with all places that have same category in that city.
How i can do it with google map APIs.
When i try to use places API it’s return json with geographic data but i cant use it with JavaScript or jQuery Json request.
$.getJSON( "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=1500&type=restaurant&keyword=cruise&key=YOUR_API_KEY", function( json ) {
console.log( "JSON Data: " + json );
});
But browser log don’t show any output.
Any example code for best way to implement my idea??!
Thank you
You're probably looking for the client-side Places Library's Nearby Search service. Take a look at this working jsfiddle.
JS code below:
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'), {
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: '500',
type: ['restaurant']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(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 marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
Hope this helps!
with this code you need only to provide city name and place types or that you can find here:
https://developers.google.com/places/web-service/supported_types
output will show 20 places in same city with type that you passed.
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
var map;
var service;
var infowindow;
var city;
function initMap() {
var cityName = document.getElementById('cityInput').value; // text input html tag
var type = document.getElementById('subCategory').value; // select input html tag
map = new google.maps.Map(document.getElementById('map'), {zoom: 14});
var cityRequest = {
query: cityName,
fields: ['name', 'geometry'],
};
//alert("find!! : " + cityName);
service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery(cityRequest, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
let city = results[0].geometry.location;
map.setCenter(city);
infowindow = new google.maps.InfoWindow();
//alert(type);
var request = {
location: city,
radius: '1000',
query: type
};
//radius is size of search area
service.textSearch(request, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) { // adding places to map
createMarker(results[i]);
}
//map.setCenter(results[0].geometry.location);
}
});
}
});
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
</script>
With this code you will show map in you web page
<div id="map" style="height: 500px; "></div>
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initMap&language=ar" async defer></script>
So I'm setting up a dynamic Google map on all of the pages on the site to show the locations you can see on every page to help users understand the locations.
It works, but works EXTREMELY slow, so slow that if it has about 40+ it can take around 1 minute to load the map and if it's more locations than that on a page it just get stuck and does not load the map.
Here is a link to see the map:
http://www.exchange-currency.org/wakefield/
And Here's the code as it is on the website, you can also see the code with view source but note the addresses are from a string with php, you can see the output on the view source of the page.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?q=<?php the_title(); ?>&key=AIzaSyDeyknfWm0qmejgXZh_VXihNcHbidewODQ"></script>
<script type="text/javascript">
var delay = 10;
var infowindow = new google.maps.InfoWindow();
var latlng = new google.maps.LatLng();
var mapOptions = {
zoom: 4,
center: latlng,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var bounds = new google.maps.LatLngBounds();
function geocodeAddress(address, next) {
geocoder.geocode({address:address}, function (results,status)
{
if (status == google.maps.GeocoderStatus.OK) {
var p = results[0].geometry.location;
var lat=p.lat();
var lng=p.lng();
createMarker(address,lat,lng);
}
else {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
nextAddress--;
delay++;
} else {
}
}
next();
}
);
}
function createMarker(add,lat,lng) {
var contentString = add;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map,
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
bounds.extend(marker.position);
}
var locations = [<?php echo $locationAddresses; ?>];
var nextAddress = 0;
function theNext() {
if (nextAddress < locations.length) {
setTimeout('geocodeAddress("'+locations[nextAddress]+'",theNext)', delay);
nextAddress++;
} else {
map.fitBounds(bounds);
}
}
theNext();
</script>
What can I do to make it work in a normal speed so its actually usable?
Here's a link to a page with more locations so you'll see what I'm talking about:
http://www.exchange-currency.org/montreal/
Thanks!
Edit:
Also if there is a way to make it load async and with clusters instead of multiple markers that would be great, can't seem to get it figured out =/
I am trying to get nearby places like gym, atm on google maps. For this I have used dburles:google-maps package. I followed the instructions on Google Maps API and did the following. The map is generated, and the center marker is shown but I am not able to generate the places markers. Can anyone point out what I am doing wrong?
This is the JS code.
Template.map.helpers({
exampleMapOptions: function() {
// Make sure the maps API has loaded
if (GoogleMaps.loaded()) {
// Map initialization options
var data=Test.findOne().address.geopoint;
var lat=data[1];
var lng=data[0];
console.log([lat,lng]);
return {
center: new google.maps.LatLng(lat, lng),
zoom: 14
};
}
}
});
Template.map.onCreated(function() {
var self = this;
GoogleMaps.ready('exampleMap', function(map) {
var marker;
// Create and move the marker when latLng changes.
self.autorun(function() {
var data=Test.findOne().address.geopoint;
var lat=data[1];
var lng=data[0];
if (! lat && ! lng)
return;
// If the marker doesn't yet exist, create it.
if (! marker) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map.instance
});
}
// The marker already exists, so we'll just change its position.
else {
marker.setPosition([lat,lng]);
}
// Center and zoom the map view onto the current position.
map.instance.setCenter(marker.getPosition());
map.instance.setZoom(14);
var pyrmont = new google.maps.LatLng(lat,lng);
// map = new google.maps.Map(document.getElementById('exampleMap'), {
// center: pyrmont,
// zoom: 15
// });
var request = {
location: pyrmont,
radius: '5000',
types: ['store']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(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]);
}
}
}
});
});
});
Solved the issue by replacing map with map.instance in places search.
I am using google maps api geolocation to get the users location via latlng, then using this location to text search for 'golf' locations around that area. Now I would like to advance from this basic map/markers view to provide place details when the user clicks on the specific map marker. The issue is when I click marker there is no response. I feel like I am one variable off but could really use some help identifying why the details & infowindo fail to appear on click?
I also saw that google is using placeID's to return details? but was unsure if that applied to the maps API detail request.
Thank you in advance for any help.
function success(position) {
var s = document.querySelector('#status');
if (s.className == 'success') {
// not sure why we're hitting this twice in FF, I think it's to do with a cached result coming back
return;
}
s.innerHTML = "found you!";
s.className = 'success';
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcanvas';
mapcanvas.style.height = '400px';
mapcanvas.style.width = '560px';
document.querySelector('article').appendChild(mapcanvas);
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
var service;
var infowindow;
var request = {
location: latlng,
radius: '3200',
query: 'golf'
};
infowindow = new google.maps.InfoWindow();
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].geometry.location);
}
}
}
function createMarker(position) {
new google.maps.Marker({
position: position,
map: map
});
}
var request = { reference: position.reference };
service.getDetails(request, function(details, status) {
marker.addListener(marker, 'click', function() {
infowindow.setContent(details.name);
infowindow.open(map, this);
});
});
}
function error(msg) {
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
error('not supported');
}
html, body, #mapcanvas {
height: 400px;
width: 400px;
margin: 0px;
padding: 0px
}
<article>
<p>Finding your location: <span id="status">checking...</span>
</p>
</article>
I see two likely issues here:
var request = { reference: position.reference };
service.getDetails(request, function(details, status) {
Here position is a LatLng, which doesn't have a reference attribute. So your getDetails call fails.
The callback function you pass to getDetails ignores the status, so you never notice any errors it reports.
Combined, this is why nothing happens.
Fix: pass the whole PlaceResult (i.e. results[i], not results[i].geometry.location) to createMarker, so you can access both the location and the Place ID.
As an aside: using reference is deprecated. Use placeId instead.
I've created a script that places a marker on a map based on the area you click your mouse over. Once that marker is placed, when your mouse hovers over the marker, an infobox should appear with the address of where the marker is placed. However, the infobox isn't showing up because when I call "info_text", it returns undefined. I realized that I needed to add in a callback function but I don't think I'm implementing it correctly. Could anyone help me fix my code? Thanks
My code:
var geocoder;
function initialize()
{
geocoder = new google.maps.Geocoder();
var event = google.maps.event.addListener;
// intializing and creating the map.
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882, 131.044922),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
event(map,'click',function(e){
var marker = placeMarker_and_attachMessage(e.latLng,map,count);
count = count + 1;
});
} // end of initalize.
function placeMarker_and_attachMessage(position,map)
{
var event = google.maps.event.addListener;
var message = ['This', 'is', 'the', 'secret', 'message'];
var marker = new google.maps.Marker({
position: position,
map: map
});
var pos = info_text(position);
alert('pos is: ' + pos);
var infowindow = new google.maps.InfoWindow({
content: 'hello'
});
event(marker,'mouseover',function(){
infowindow.open(map,this);
});
event(marker,'mouseout',function(){
infowindow.close();
});
} // end of function.
function info_text(position)
{
var lat = parseFloat(position.lat());
var lng = parseFloat(position.lng());
alert('lat,lng is: ' + (lat,lng));
var latlng = new google.maps.LatLng(lat,lng);
alert('just before geocode');
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
alert('in info_text If statement');
if(results[1])
{
alert('in inner if statement');
var finalResult = myCallback(results[1].formatted_address);
return finalResult;
}
else
{
alert('no results found');
}
}
else
{
alert('could not pinpoint location');
}
});
}
function myCallback(loc)
{
alert('i have a location!');
return loc;
}
google.maps.event.addDomListener(window, 'load', initialize);
Your function info_text doesn't return anything, so this line:
var pos = info_text(position);
is where pos is undefined.
You need to include:
return something;
at some point in your function (like you have done further down).
Added
Your function myCallback returns a value, but where it is used:
myCallback(results[1].formatted_address);
it doesn't store the return-value anywhere - it is just discarded.