Google Places API not working with getCurrentPosition Geolocation in Ionic app - javascript

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).

Related

Show nearby Places in Google Maps in Meteor

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.

How to show geolocated tweets on a map

I have been playing around with the twitter API getting random tweets or even geo tagged tweets and also with the google maps API. However I want to combine this two and try and show geo tagged tweets on a google map. Here is my code for getting the geo tagged Tweets which work fine.
var geo = (geo.coordinates[0], geo.coordinates[1])
//var geo = (34.052234, -118.243685)
client.get('search/tweets', { q:string.teamname, geocode: geo, count: 5},
function searchTweets(err, data, response) {
for(var index in data.statuses){
var tweet = data.statuses[index];
console.log(tweet.text);
console.log(tweet.geo.coordinates)
}
});
On a different file, I generated a map based on Longitude and Latitude, and I had the understanding that once I had retrieved the coordinates for the tweets, I could represent the tweets on a Google Map in the same way. However, my code is not working. My question is, how would I combine both pieces of code to generate a map which is marked with geo located Tweets?
function initialize() {
var myLatlng = new google.maps.LatLng(geo.coordinates[0], geo.coordinates[1]);
var mapOptions = {
center: myLatlng
zoom: 10,
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Tweet});
var infowindow = new google.maps.InfoWindow({
content: 'Geo tagged Tweet',
maxWidth:200 });
infowindow.open(map,marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker); });
}
google.maps.event.addDomListener(window, 'load', initialize);
I would do something like this (untested - I'm just writing down some thoughts).
1) You should strip down init so that it just contains the map set up. Ensure map is declared outside of the function, and include a call to the function that fetches your data using the lat/lng data.
var map;
function initialize() {
var lat = geo.coordinates[0];
var lng = geo.coordinates[1]
var myLatlng = new google.maps.LatLng(lat, lng);
var mapOptions = { center: myLatlng, zoom: 10 }
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
getData(lat, lng, processData);
}
2) You wrap your data fetching code in a new function declaration, which accepts lat/lng data, and a callback.
function getData(lat, lng, callback) {
client.get('search/tweets', { q:string.teamname, geocode: geo, count: 5},
function searchTweets(err, data, response) {
callback(data.statuses);
}
)
};
3) Process the tweet information. For each tweet create a marker (add the marker to an array of markers) and update the map
function processData(data) {
var markers = [];
for (var i = 0, l = data.length; i < l; i++) {
var marker = new google.maps.Marker({
id: i,
position: myLatlng(data[i].geo.coordinates[0], data[i].geo.coordinates[1),
map: map,
title: "Tweet"
});
markers.push(marker);
var infowindow = new google.maps.InfoWindow({
content: data[i].text,
maxWidth: 200
});
infowindow.open(map, marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
}

using google map geocoder.geocode before initializing the map

I have created a nice Google map form that gets clients data from the database ( with a jQuery post call to php) and loads it into the clients_details. if clients_details[]['location'] which is Latlng is provided in the database all works well and marker gets displayed as expected. Problem is that when clients_details[]['location'] is not provided then I use the address from clients_details[]['address'] and try to get position of the marker by using geocoder.geocode. However surprisingly every time the code gets to the geocoder it jumps from it and comes back to it after it initialized the map ! so markers wont get added to the map !
I am assuming it has something to do with JavaScript function priorities but not sure how
<script>
var clients_details // getting this from database;
var infowindow =[];
var geocoder;
var map;
function showMarkers(clients_details)
{
var marker = [];
for (var i = 0; i < clients_details.length; i++)
{
content = 'Test Content' ;
infowindow[i] = new google.maps.InfoWindow({
content: content,
maxWidth: 350
});
var client_location;
if (clients_details[i]['location'] !== null)
{
// Geting Lat and Lng from the database string
LatLng = clients_details[i]['location'];
client_location = new google.maps.LatLng (LatLng);
}
else
{
client_address = clients_details[i]['address'];
geocoder.geocode(
{ 'address': client_address},
function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
client_location = results[0].geometry.location;
}
else
alert('Geocode was not successful for the following\n\
reason: ' + clients_details[i]['name']+'\n' + status);
});
}
marker[i] = new google.maps.Marker({
position: client_location,
map: map,
title: clients_details[i]['name']
});
// Add 'click' event listener to the marker
addListenerMarkerList(infowindow[i], map, marker[i]);
}// for
}// function
The
marker[i] = new google.maps.Marker({
position: client_location,
map: map,
title: clients_details[i]['name']
});
Code should be inside the callback in the geocoder.geocode call.
Because in your code the client_location is computed after the marker[i].
What you could do is:
compute the client_location and when the client_locolation is computed
then compute the marker[i]
So your code could be like this:
// ... your code as is
geocoder.geocode(
{ 'address': client_address},
function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
client_location = results[0].geometry.location;
// closure needed, for the marker[i] to work correctly,
// because we are in a loop on i
(function (i) {
marker[i] = new google.maps.Marker({
position: client_location,
map: map,
title: clients_details[i]['name']
});
})(i);
}
else
{
alert('Geocode was not successful for the following\n\
reason: ' + clients_details[i]['name']+'\n' + status);
}
}
);
// .... your code as is
You need to bind your call back function to the right event. Bind the initialize of the map to window load. Inside that function then call the rest of the marker/geocoder logic. As extracted from their documentation:
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882, 131.044922)
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
title: 'Click to zoom'
});
google.maps.event.addListener(map, 'center_changed', function() {
// 3 seconds after the center of the map has changed, pan back to the
// marker.
window.setTimeout(function() {
map.panTo(marker.getPosition());
}, 3000);
});
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(8);
map.setCenter(marker.getPosition());
});
}
google.maps.event.addDomListener(window, 'load', initialize);

Google Maps API with Geolocation and Places Search

I'm using the Google Maps and places API. I'm trying to have the map show current location WITH surrounding restaurants, cafes, and bars. At this point the map loads and the geolocation is working. I can't seem to get the place markers to show up. I have no idea what I'm missing as I'm learning javascript as quickly as possible.
Any help would be very much appreciated. Thank You!
Here is my current code:
<script>
var map;
var service;
var marker;
var pos;
var infowindow;
function initialize()
{
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
panControl: false,
streetViewControl: false,
mapTypeControl: false,
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//HTML5 geolocation
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position)
{
pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
infowindow = new google.maps.InfoWindow({map: map,position: pos,content: 'You Are Here'});
var request = {location:pos,radius:500,types: ['restaurant, cafe, bars']};
map.setCenter(pos);
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
},
function()
{
handleNoGeolocation(true);
});
}
else
{
handleNoGeolocation(false);
}
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);
</script>
Check that your script call to the Google API includes a reference to the places library. For example:
<script src="http://maps.googleapis.com/maps/api/js?key=yourAPIkey&libraries=geometry,places&sensor=true&language=en"></script>
In this line of code:
var request = {location:pos,radius:500,types: ['restaurant, cafe, bars']};
instead of types: write keyword:

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});

Categories

Resources