我需要使用Google Javascript API而不是使用google-api npm模块来显示位置。因此,基本上,我需要在NodeJs服务器中利用脚本代码。但是,我遇到了错误-
Cannot GET /views/location.html
当我在浏览器中输入 localhost:8080 / views / location.html
我需要接受的位置,然后使用Javascript API将其显示在地图上。 请指导我。 我创建了以下页面-
server.js
var express = require('express');
var app = express();
const path = require('path');
var restify = require('restify');
var bodyParser = require('body-parser');
var mysql = require('mysql');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static ('public'));
app.set('view engine', 'ejs');
var cors = require('cors') // Not required.
app.use(cors());
app.use(express.static('public'))
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use('/', require('./display.js'));
app.get('/', function(req, res) {
res.redirect('./views/location.html');
});
app.listen(8080,(req,res)=>{
console.log('server running on port 8080')
})
display.js
var express = require('express');
var router = express.Router();
var map, infoWindow;
router.post('/', seekLocation);
//router.post('/abc', tmsServer);
module.exports = router;
//working code below
function seekLocation(req, res) {
console.log("INSIDE NODE JS CONTROLLER OF seekLocation");
console.log("BODY IS ", req.body);
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
console.log("Inside seekLocation.js")
location.html
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 425px;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDXlYBEQbsnyDl-N1ntSqjMjZaks8&callback=initMap">
</script>
</body>
</html>