Prash's Blog

Maps example with Google Maps and Nodejs April 19, 2012

Filed under: Nodejs — prazjain @ 11:19 am
Tags: , ,

This is a short piece of code to show maps in a nodejs application.

We will need some 3rd party modules, so install these modules

npm install ejs
npm install express
npm install geohash
  • EJS is a dependency for Express.
  • Express is a framework ExpressJS built on top of ConnectJS, it allows robust routing, view rendering, and templating. ExpressJS Details here.
  • GeoHash module is needed to convert geohashes to latitude and longitude coordinates. Geohash is used to uniquely identify a geographical point, it uses latitude and longitude to create a composite string that can be transmitted, stored. Datastores that do not have strong spatial indexing support, geohashes can be used. But having said that, in our application below, there is nothing stopping you from directly entering lat and lon coordinates in url querystring, it is just that geohashes will make the url shorter. Just to note that with a geohash you can trim characters from the right side, but as you trim, the precision of geohash reduces.

Now lets start with the code. Create a file index.js :

var express = require("express");
var app = express.createServer();
var geohash = require("geohash").GeoHash;

// route routing is very easy with express, this will handle the request for root directory contents.
// :id is used here to pattern match with the first value after the forward slash.
app.get("/:id",function (req,res)
	{
                //decode the geohash with geohash module
		var latlon = geohash.decodeGeoHash(req.params["id"]);
		console.log("latlon : " + latlon);
		var lat = latlon.latitude[2];
		console.log("lat : " + lat);
		var lon = latlon.longitude[2];
		console.log("lon : " + lon);
		zoom = req.params["id"].length + 2;
		console.log("zoom : " + zoom);
                // now we use the templating capabilities of express and call our template to render the view, and pass a few parameters to it
		res.render("index.ejs", { layout: false, lat:lat, lon:lon, zoom:zoom, geohash:req.params["id"]});
	});

app.listen(9999);

Now create a folder ‘views’ in your current working directory (where you just saved index.js), and inside it create index.ejs with the code below.

<html>
	<head> 
		<title>GeoHash</title>
		<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
		<script type="text/javascript">
			var loadMap = function() 
			{
				var myOptions = {
				  center: new google.maps.LatLng(<%=lat%>, <%=lon%>),
				  zoom: <%=zoom%>,
				  mapTypeId: google.maps.MapTypeId.ROADMAP
				};
				var map = new google.maps.Map(document.getElementById("map"),
					myOptions);
			};
			window.onload= loadMap;
		</script>
	</head>
	<body>
		<div id="map" style="width:500px;height:500px;"></div>
	</body>
</html>

Here we define a loadMap function that will be called on window load, all we do is create a map instance with google.map.Map and give it the options passed as parameter passed from index.js.

With all this you are ready to go. Start your node application :

node index.js

Now as this is running on your localmachine, try this url : http://localhost:9999/gcpvj0fb970t1

As you will have noticed by now “gcpvj0fb970t1”, is a geohash for a location, try the code to find what location it is!

Cheers

Advertisements
 

11 Responses to “Maps example with Google Maps and Nodejs”

  1. rsh123 Says:

    Hi, I got an error when trying to connect localhost : Error: failed to locate view “index.ejs”
    I’ve try with older version of express but still. Isn’t it error in line 19 of index.js file ?
    Tx
    Flo

    • rsh123 Says:

      full text is :
      Error: failed to locate view “index.ejs”
      at Function.compile (/home/vivaldi/dev/google-map-nodejs/view/node_modules/express/lib/view.js:61:15)
      at ServerResponse._render (/home/vivaldi/dev/google-map-nodejs/view/node_modules/express/lib/view.js:417:18)
      at ServerResponse.render (/home/vivaldi/dev/google-map-nodejs/view/node_modules/express/lib/view.js:318:17)
      at /home/vivaldi/dev/google-map-nodejs/view/index.js:19:7
      at callbacks (/home/vivaldi/dev/google-map-nodejs/view/node_modules/express/lib/router/index.js:272:11)
      at param (/home/vivaldi/dev/google-map-nodejs/view/node_modules/express/lib/router/index.js:246:11)
      at param (/home/vivaldi/dev/google-map-nodejs/view/node_modules/express/lib/router/index.js:243:11)
      at pass (/home/vivaldi/dev/google-map-nodejs/view/node_modules/express/lib/router/index.js:253:5)
      at Router._dispatch (/home/vivaldi/dev/google-map-nodejs/view/node_modules/express/lib/router/index.js:280:4)
      at Object.handle (/home/vivaldi/dev/google-map-nodejs/view/node_modules/express/lib/router/index.js:45:10)

  2. rsh123 Says:

    it was my mistake ! i get it

  3. I get an error says
    module.js:340
    throw err;
    ^
    Error: Cannot find module ‘express’
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object. (D:\files\index.js:1:77)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)

    but i already installed ‘express’ as given by you.
    my location for express is “C:\Program Files\nodejs\node_modules\express”

    can you please suggest something to resolve this error.

    Thanks.

  4. […] Maps example with Google Maps and Nodejs […]

  5. srikanth ganta Says:

    Reblogged this on Srikanth's Blog.

  6. Kishore Says:

    Not able to call ejs template in Node js, it is giving (TypeError: res.render is not a function) any support please.

    Code:
    var http=require(“http”);
    http.get(“API”, function (res)
    {
    var body = ”;
    res.on(‘data’, function(chunk){
    body += chunk;
    });
    res.on(‘end’, function(){
    var jsonData = JSON.parse(body);
    for(var i=0; i< jsonData.length; i++) {
    var lat = jsonData[i].Latitude;
    console.log("lat : " + lat);
    var lon = jsonData[i].Longitude;
    console.log("lon : " + lon);
    var zoom = 11;
    console.log("zoom : " + zoom);
    res.render("index.ejs", { layout: false, lat:lat, lon:lon, zoom:zoom});
    }
    });

    });

    Output:
    TypeError: res.render is not a function
    at IncomingMessage. (C:\index.js:51:7)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)

  7. Kishore Says:

    Not able to call ejs template in Node js, it is giving (TypeError: res.render is not a function) any support please..

    my code is :
    var http=require(“http”);
    http.get(“API”, function (res)
    {
    var body = ”;
    res.on(‘data’, function(chunk){
    body += chunk;
    });
    res.on(‘end’, function(){
    var jsonData = JSON.parse(body);
    for(var i=0; i< jsonData.length; i++) {
    var lat = jsonData[i].Latitude;
    console.log("lat : " + lat);
    var lon = jsonData[i].Longitude;
    console.log("lon : " + lon);
    var zoom = 11;
    console.log("zoom : " + zoom);
    res.render("index.ejs", { layout: false, lat:lat, lon:lon, zoom:zoom});
    }
    });

    });

    Error:
    TypeError: res.render is not a function
    at IncomingMessage. (C:\index.js:51:7)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s