通过Google地图显示Facebook信息

时间:2015-05-24 10:21:05

标签: javascript node.js facebook google-maps facebook-graph-api

好的我正在尝试创建一个同时使用gmaps和fb好友列表的Web应用程序。第一步是能够在谷歌地图上显示当前位置,这应该是登录的人的姓名和图片。我目前只有你在登录Facebook时才能查看地图,但除此之外,我是无法让2进行互动。

我的maps.js文件如下所示:

"use strict";
var map;
var markers = []

function initialize() {
  var mapOptions = {
    zoom: 16
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  google.maps.event.addDomListener(window, 'load', initialize);
  google.maps.event.addDomListener(window, "resize", function() {
   var center = map.getCenter();
   google.maps.event.trigger(map, "resize");
   map.setCenter(center); 
  });

  // Try HTML5 geolocation
  if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var pos = new google.maps.LatLng(position.coords.latitude,
                                       position.coords.longitude);


      socket.emit('marker', {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      });

      var infowindow = new google.maps.InfoWindow({
        content: '<%= user.displayName %>'
      });

      var markerPos = new google.maps.Marker({
        map: map,
        position: pos,
        title: '<%= user.displayName %>'
      });

      google.maps.event.addListener(markerPos, 'click', function() {
        infowindow.open(map,markerPos);
      });

      map.setCenter(pos);
    }, function() {
      handleNoGeolocation(true);
    });
  } else {
    // Browser doesn't support Geolocation
    handleNoGeolocation(false);
  }
}

function handleNoGeolocation(errorFlag) {
  if (errorFlag) {
    var content = 'Error: The Geolocation service failed.';
  } else {
    var content = 'Error: Your browser doesn\'t support geolocation.';
  }

  var options = {
    map: map,
    position: new google.maps.LatLng(60, 105),
    content: content
  };

  var infowindow = new google.maps.InfoWindow(options);
  map.setCenter(options.position);
}

google.maps.event.addDomListener(window, 'load', initialize);

// Add a marker to the map 
function addMarker(location, text) {
    text = text || '';

    var marker = new google.maps.Marker({
        position: location,
        map: map
    });

    var infowindow = new google.maps.InfoWindow();

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.setContent(text); 
      infowindow.open(map,marker);
    });

    return marker;
}

服务器文件如下所示:

var express = require('express')
var passport = require('passport')
var util = require('util')
var FacebookStrategy = require('passport-facebook').Strategy
var logger = require('morgan')
var session = require('express-session')
var sessionStore = require('sessionstore');
var bodyParser = require("body-parser")
var cookieParser = require("cookie-parser")
var methodOverride = require('method-override');
var port = process.env.PORT || 3000
var io = require('socket.io')(http);
var http = require('http').Server(app);
var markers = [];
var server = require('http').createServer(app);
var passportStrategy = require('../utils/passport-strategy');

var FACEBOOK_APP_ID = "";
var FACEBOOK_APP_SECRET = "";

passport.use(passportStrategy.facebook);

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});

var sessionData = session({
  store: sessionStore.createSessionStore(),
  secret: "your_secret",
  cookie: { maxAge: 2628000000 },
  resave: true,
  saveUninitialized: true
});

io.use(function(socket, next){
  sessionData(socket.request, socket.request.res, next);
});

passport.use(new FacebookStrategy({
    clientID: FACEBOOK_APP_ID,
    clientSecret: FACEBOOK_APP_SECRET,
    callbackURL: "http://localhost:3000/auth/facebook/callback"
  },
  function(accessToken, refreshToken, profile, done) {

    process.nextTick(function () {

      return done(null, profile);
    });
  }
));




var app = express();

  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(sessionData);
  app.use(logger());
  app.use(cookieParser());
  app.use(bodyParser());
  app.use(methodOverride());
  app.use(session({ secret: 'keyboard cat' }));

  app.use(passport.initialize());
  app.use(passport.session());
  app.use(express.static(__dirname + '/public'));


app.get('/', function(req, res){
  res.render('index', { user: req.user });
});

app.get('/account', ensureAuthenticated, function(req, res){
  res.render('account', { user: req.user });
});

app.get('/login', function(req, res){
  res.render('login', { user: req.user });
});


app.get('/auth/facebook',
  passport.authenticate('facebook'),
  function(req, res){
  });


app.get('/auth/facebook/callback', 
  passport.authenticate('facebook', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

app.get('/mapjs', function(req, res){
  res.sendFile(__dirname + '/public/map.js', { user: req.user });
});

io.on('connection', function(socket){
    console.log('a user connected');

    socket.on('marker', function(data) {
      data.socketId = socket.id;

      markers[socket.id] = data;


  console.log('marker latitude: ' + data.lat + ', marker longitude:' + data.lng);
    socket.broadcast.emit('show-marker', data);
    });

});

app.listen(port, function(){
  console.log('five minute catch up is on port 3000');
});

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login')
}

module.exports = server;

index.ejs如下所示:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Five Minute Catchup</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
    <link rel="stylesheet" href="app/styles/main.css">
<!--    Internal map style (cant remove)-->
      <style type="text/css">
      html, body, #map-canvas { height: 90%; margin: 0; padding: 0;}
    </style>
<!--   Public API  -->
     <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
  </head>

  <body>



  <% if(!user) { %>
  <div class="header">
        <div class="navbar navbar-default" role="navigation">
          <div class="container">
            <div class="navbar-header">



              <a class="navbar-brand" href="#/">Five Minute Catchup</a>
            </div>

            <div class="collapse navbar-collapse" id="js-navbar-collapse">

              <ul class="nav navbar-nav">
                <li ><a href="#/">Home</a></li>
                <li><a href="/account">Account</a></li>
                <a href="/auth/facebook"><img src="login-with-facebook.png" width="154" height="22"></a>

              </ul>
            </div>
          </div>
        </div>
      </div>

      <h2>Welcome! Please log in.</h2>

      <% } else { %>

        <div class="header">
        <div class="navbar navbar-default" role="navigation">
          <div class="container">
            <div class="navbar-header">

              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#js-navbar-collapse">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>

              <a class="navbar-brand" href="#/">Five Minute Catchup</a>
            </div>

            <div class="collapse navbar-collapse" id="js-navbar-collapse">

              <ul class="nav navbar-nav">
                <li ><a href="#/">Home</a></li>
                <li><a href="/account">Account</a></li>
                <li><a href="/logout">Logout</a></li>
              </ul>
            </div>
          </div>
        </div>
      </div>

        <h2>Hello, <%= user.displayName %></h2>
    <div id="map-canvas"></div>
      <% } %>




    <div class="footer">
      <div class="container">
        <p><span class="glyphicon glyphicon-heart"></span> from the Five Minute Catchup team</p>
      </div>
    </div>






        // <!-- <script src="public/map.js"></script> -->

        <!-- socket scripts -->
        <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
      <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
      <script src="/mapjs"></script>
      <script>
        var socket = io();
        //Listen for other users markers
        socket.on('show-marker', function(data) {
          console.log(data);
          var loc = new google.maps.LatLng(data.lat,
                                         data.lng);
          addMarker(loc, data.socketId);
        });
      </script>
</body>
</html>
抱歉不得不复制并粘贴整个文件,我不想错过一些可能相关的代码!

任何有助于在谷歌地图信息窗口中获取fb名称和图片网址的帮助将不胜感激!

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要创建自定义制作者并创建一个调用Facebook详细信息的函数。 在jsfiddle上看到这个演示 http://jsfiddle.net/mfirdaus/DVKEj/

var data = [{
profileImage:"http://www.gravatar.com/avatar/d735414fa8687e8874783702f6c96fa6?
s=90&d=identicon&r=PG"

for(var i=0;i<data.length;i++){
new CustomMarker(new google.maps.LatLng(data[i].pos[0],data[i].pos[1]), map,   
data[i].profileImage)
}