Show nearby Places in Google Maps in Meteor - javascript

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.

Related

Google Maps geocode() loop to place markers

I have an array with location data with one of the items being an address - ie. "123 Main Street, San Francisco, California". I want to take that address, turn it into coordinates, then use those coordinates to plot a marker on the map. To do this, I know I need to use geocode(), so I added that part into my loop.
If I were to use latitude and longitude in my array instead of the address, I can get this to work fine. But, since I added geocode() into my loop, I can only get the first location in the array to display a marker.
I have seen some similar questions on here that suggest using callback() but I did not understand it. I've also seen a suggestion to add a delay to geocode() of 0.5 seconds which worked for the poster, but comments said it may not load all locations on slower internet speeds.
How can I fix this to show all locations in the correct way?
// Create the map with markers.
function createmap(zoomlevel, centerpos, showDot)
{
// Create the map canvas with options.
var map = new google.maps.Map(document.getElementById('map-canvas'), {
scrollwheel: false,
draggable: true,
mapTypeControl: false,
zoom: zoomlevel,
center: new google.maps.LatLng(40.577453, 2.237408), // Center the map at this location.
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker, i;
// For each location in the array...
for (i = 0; i < locations.length; i++)
{
// Get the coordintes for the address.
var geocoder = new google.maps.Geocoder();
var address = locations[i][5]; // ***This variable will output the address.***
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location_latitude = results[0].geometry.location.lat();
var location_longitude = results[0].geometry.location.lng();
// Create the map marker icon (SVG file).
var marker_icon = {
url: '//'+domain+'/__NEW__/_backend/assets/img/map-marker.svg',
anchor: new google.maps.Point(25,50),
scaledSize: new google.maps.Size(50,50)
}
// Place the marker on the map.
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location_latitude, location_longitude),
map: map,
icon: marker_icon
});
}
});
}
}
This is how I am placing map markers on Google Maps:
<script type="text/javascript">
let map;
let parameters;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: #Model.Latitude , lng: #Model.Longitude },
zoom: #Model.Zoom,
});
#foreach (var asset in dbService.Assets)
{
#if (asset.State != Models.AssetState.deleted)
{
#:parameters = 'Id = #asset.Id\n' + 'Temperature = #asset.Temperature\n' + 'Moisture = #asset.Moisture\n';
#:setMarker('#asset.Latitude', '#asset.Longitude', '#asset.State');
}
}
}
function getIconByState(state) {
if (state == 'non_functional') {
return 'non-functional.png';
}
else if (state == 'under_maintenance') {
return 'under-maintenance.png';
}
else if (state == 'functional') {
return 'functional.png';
}
}
function setMarker(lat, lng, state) {
var markerjs = new google.maps.Marker({
icon: getIconByState(state),
position: new google.maps.LatLng(lat, lng),
});
markerjs.setMap(map);
let infowindow = new google.maps.InfoWindow({
content: parameters,
});
markerjs.addListener("click", () => {
infowindow.open(map, markerjs);
});
}
</script>
//this is how to use the callback
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY&callback=initMap&libraries=&v=weekly"
defer></script>
In this code, I use the latitude and longitude to place a marker on the Map.
If you want to extract the latitude and longitude from an address, then use geocoder API in the following way:
<script type="text/javascript">
function setCoordinates() {
let address = document.getElementById('zip').value;
if (address) {
let geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById('latitude').value = results[0].geometry.location.lat();
document.getElementById('longitude').value = results[0].geometry.location.lng();
}
else {
console.log('geocoding failed');
}
});
}
}
else {
alert('Please enter postal code to use this functionality');
}
}
</script>

Google Places API not working with getCurrentPosition Geolocation in Ionic app

Trying to get Google Places API to notice my location and apply the functions below. Very new to this and not sure what I am doing wrong below as the API and all the functions works initially, but after I'm asked for my location, it shows where I am but nothing else works/aren't working together.
Cordova Geolocation plugin I added to my ionic app:
cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-geolocation.git
App.js
app.controller("MapController", function($scope, $ionicLoading) {
var map;
var infowindow;
var request;
var service;
var markers = [];
google.maps.event.addDomListener(window, 'load', function() {
var center = new google.maps.LatLng(42.3625441, -71.0864435);
var mapOptions = {
center:center,
zoom:16
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
navigator.geolocation.getCurrentPosition(function(pos) {
map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
var myLocation = new google.maps.Marker({
position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
map: map,
title: "My Location"
});
});
$scope.map = map;
request = {
location: center,
radius: 1650,
types: ['bakery', 'bar']
};
infowindow = new google.maps.InfoWindow();
var 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++) {
createMarker(results[i]);
}
}
}
function createMarker(place){
var placeLoc = place.geometry.location;
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);
});
}
});
});
When you get the position, you update the map's location, but you don't run a new Nearby Search.
So I think you want to call service.nearbySearch(...) in the getCurrentPosition callback.
You may also want to have your nearbySearch callback keep an array of the markers created via createMarker, so you can remove them when you run a new search (e.g. by calling marker.setMap(null) on each old marker).

How to use an existing marker for Google Maps API directionService instead of defining a new one?

I'm using Google Maps API to show directions to a location.
On page load, I set a marker on the map: (FYI: I haven't included the coordinates, but you can assume they are defined)
var destination = [xxx, yyy, 11, xxx, yyy]; //x-coord,y-coord,zoom,x-center,x-center
var dublin = [xxx, yyy, 11, xxx, yyy]; //x-coord,y-coord,zoom,x-center,x-center
var directionsService = new google.maps.DirectionsService();
var directionsDublin;
function initialize() {
directionsDublin = new google.maps.DirectionsRenderer();
var centerMap = new google.maps.LatLng(destination[3],destination[4]);
map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: centerMap,
zoom: destination[2]
});
marker1 = new google.maps.Marker({
position: new google.maps.LatLng(destination[0], destination[1]),
map: map
});
marker1.setAnimation(google.maps.Animation.DROP);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
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);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
So the code above displays the map with a marker on it.
I now have a button #tNorth. Clicking it will show a route from a defined location. Clicking again will remove the route and return to the original view.
$(document).ready(function() {
$( "#tNorth" ).on( "click", function() {
if ($("#north").css('display') != 'none') {
//set zoom and center
map.setZoom(destination[2]);
map.setCenter(new google.maps.LatLng(destination[3], destination[4]));
//remove the route
directionsDublin.setMap(null);
//remove the text
$("#north").css('display':'none');
}
else {
//create travel route
var request2 = {
origin: new google.maps.LatLng(dublin[0], dublin[1]),
destination: new google.maps.LatLng(destination[0], destination[1]),
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
//display route on map
directionsDublin.setMap(map);
directionsService.route(request2, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDublin.setDirections(result);
}
});
//add the text
$("#north").css('display':'block');
}
});
});
This is my first use of the Maps API so I'm pretty happy!!
However, when the route is displayed, it places 2 new markers on the page. Since the destination marker is already on the page, it gets overlayed by the new marker.
Is there a way for me to, instead of defining destination: new google.maps.LatLng(destination[0], destination[1]), that I could instead define something like destination: marker1??
It would be nicer than displaying two markers over each other...
Use {suppressMarkers:true} in the DirectionRendererOptions to prevent the DirectionsRenderer from adding markers to the map (it will still show the route)
directionsDublin = new google.maps.DirectionsRenderer({suppressMarkers:true});

Draw a route on google map on click

What I am trying to do is on click google maps, place a marker, and draw a route between these markers. This works but the problem I'm facing is as follows: (please view the images of map)
(1) When I click three times on google map, the route is drawn perfectly. (meaning first I click A then B and then C location)
(2) Then if I click a forth time on google map, the location must be D but the map looks as follows:
Here the B location is replaced or hidden and in place of B, C is displayed and same...
(3) If I click a fifth time on google map, the location should be E, but the map looks like:
In short, if I click five times on google map, the route should be 'A,B,C,D,E'. Instead it is displayed as 'A,E,F,G,H'.
The full code is as follows:
<script>
var waypts=[];
var ways=[];
function initialize() {
var geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(23.0171240, 72.5330533),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
google.maps.event.addListener(map, 'click', function(e) {
placeMarker(e.latLng, map);
var input=e.latLng;
var lat = parseFloat(input.lat());
var lng = parseFloat(input.lng());
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var add=results[1].formatted_address;
waypts.push({
location:add,
stopover:true
});
//alert(JSON.stringify(waypts));
if(waypts.length>2) {
for ( var i = 1; i <= waypts.length - 2 ; i++) {
ways.push({
location:waypts[i].location,
stopover:true
});
}
}
makeroute(waypts);
}
});
});
<!-- ************** for route between markers ******************* -->
function makeroute(waypts){
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: false, //false it if you want a marker from the direction service
polylineOptions: {
strokeColor: 'green', //"black",
strokeOpacity: 1.0,
strokeWeight: 3
}
});
var start = waypts[0].location;//"Bopal, Ahmedabad, Gujarat, India";
var end = waypts[waypts.length-1].location;//"Nikol, Ahmedabad, Gujarat, India";
if(waypts.length>1) {
var request = {
origin:start,
destination:end,
waypoints:ways,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
directionsDisplay.setMap(map);
google.maps.event.addDomListener(window, 'load', initialize);
}
}
}
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
//map: map
});
// map.panTo(position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
LATER UPDATE
I use directionsDisplay.setPanel(document.getElementById('a')); for the full route information.
It display when ever I click on google map, the routes is repeat. Meaning on the first click A, on second click A to B, on third A to B to C not B to C etc. It also display that some points merged. For example B and C have same location and on the map C is only displayed.
You need to clear out the waypoints array ("ways") each time you add a new point. Each time you add a point, the start point stays the same but the old end point needs to be added to the waypoints array, and the new point is the end point. Currently you never clear out the "ways" array. Changing this:
if(waypts.length>2) {
for ( var i = 1; i <= waypts.length - 2 ; i++) {
ways.push({
location:waypts[i].location,
stopover:true
});
}
}
makeroute(waypts);
To this:
if(waypts.length>2) {
ways = [];
for ( var i = 1; i <= waypts.length - 2 ; i++) {
ways.push({
location:waypts[i].location,
stopover:true
});
}
}
makeroute(waypts);
Works for me.

How do I get more results from Google Places / Maps

I am using google maps and I am trying out places API, but something makes me wonder...
If you load maps.google.com and go to Kuala Lumpur, then type "food" in the search-box, you will see hundreds of restaurants on the map. I would like to get these into my own maps.
Using the Places API, I have pretty much copied their example code:
function initialize() {
var plat = 3.15;
var plong = 101.7;
var ppos = new google.maps.LatLng(plat, plong);
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
draggable: false,
zoom: 10,
center: ppos
};
map = new google.maps.Map(document.getElementById("mapcanvas"), mapOptions);
var request = {
location: ppos,
radius: '10000'
};
infowindow = new google.maps.InfoWindow();
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++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: place.icon
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent("<b>" + place.name + "</b><br/>" + place.vicinity);
infowindow.open(map, this);
});
}
When I execute this code, I do get results, but only very few and only major locations like a few malls and museums. So, How do I get all that beautiful data, that I see on Google's own map?
So it turned out there were a number of problems:
Categorization is broken in Inodesia, so using keyword instead solved the problem, as in:
var request= {
location: ppos,
radius: 10000,
keyword: 'restaurant' }
keyword takes a string rather than an array, and radius takes a number rather than a string. You can see a summary of the types for the request here: http://code.google.com/apis/maps/documentation/javascript/reference.html#PlaceSearchRequest

Categories

Resources