Solved

User Current Location

Posted on 2009-07-03
47
355 Views
Last Modified: 2012-06-27
I am trying to create a Java web application with google api.  I will be able to locate a user's location and mark it on the google map. Then, I need to store the information of user's location. How exactly I can do this?

I try to use google.loader.ClientLocation with JavaScript to get user's information.  So, I tried to call through Java; therefore, I can store information into some table.  However, I keep having some error message said "some variable is not defined" or "google is not defined".

What can I do to make this work?
0
Comment
Question by:xenia27
  • 21
  • 11
  • 8
  • +2
47 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 24770733
>>So, I tried to call through Java

How? Please post code
0
 
LVL 15

Expert Comment

by:fsze88
ID: 24770749
I need to store the information of user's location?
could you try store user's information into cookies?
0
 

Author Comment

by:xenia27
ID: 24770751
Error Message...
javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "cl" is not defined. (<Unknown source>#1) in <Unknown source> at line number 1
      at com.sun.script.javascript.RhinoScriptEngine.invoke(Unknown Source)
      at com.sun.script.javascript.RhinoScriptEngine.invokeFunction(Unknown Source)
      at com.unet.googleproject.server.GreetingServiceImpl.greetServer(GreetingServiceImpl.java:44)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:527)
      at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:166)
      at com.google.gwt.user.server.rpc.RemoteServiceServlet.doPost(RemoteServiceServlet.java:86)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:713)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:806)
      at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
      at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1093)
      at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
      at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084)
      at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:360)
      at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
      at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
      at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:712)
      at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
      at com.google.apphosting.utils.jetty.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:54)
      at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:139)
      at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:306)
      at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:139)
      at org.mortbay.jetty.Server.handle(Server.java:313)
      at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:506)
      at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:844)
      at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:644)
      at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:205)
      at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:381)
      at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:396)
      at org.mortbay.thread.BoundedThreadPool$PoolThread.run(BoundedThreadPool.java:442)
my html file...

  	<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true">
 

	var cl;

  	google.load("maps", "2.x");

    if (google.loader.ClientLocation)

        cl = google.loader.ClientLocation;

    function GetClientLatitude()

    {
 

        return cl.latitude;

    }
 

    function GetClientLongitude()

    {

        return cl.longitude;

    }

    

    function sumTwoValue(var1, var2)

    {

        return var1 + var2;

    }
 

    </script>
 

my java file...

		// getting engine

		ScriptEngineManager mgr = new ScriptEngineManager();

		ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");

		Invocable invocableEngine = (Invocable)jsEngine;

		String value = new String();
 

		try {

		jsEngine.eval("function GetClientLatitude() {" +

		" return cl.latitude;" +

		"}");
 
 

		// (Java-|ëScript Method&púÞ³<

		System.out.println("return value from javascript is : " +

		invocableEngine.invokeFunction("GetClientLatitude"));

		value = invocableEngine.invokeFunction("GetClientLatitude").toString();
 

		} catch (ScriptException ex) {

		ex.printStackTrace();

		} catch (NoSuchMethodException ex) {

		ex.printStackTrace();

		}

Open in new window

0
 

Author Comment

by:xenia27
ID: 24770756
What's wrong with my code?

Cookie?  Which one is easiest one?
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 24770758
xenia27,

Java and Javascript are two completely different languages and run at different times in a web page's "life."  Java would be done by the server or maybe an applet; Javascript is run by the browser.  This is why variables of one won't be available to the other.

What exactly do you mean a Java web app?  Google's API uses Javascript and you would use Javascript to work with it in your browser.  At least the part that is used for maps?  What is the code you are trying to use to locate the location?  What API exactly?  The ClientLocation property I have seen in Google's API is related to their AJAX API.  It is Javascript which is used to work with it.  If you are having a problem with it then please provide more specifics on the code and when this problem occurs in relation to what you are doing.

Let me know if you have any questions or need more information.

b0lsc0tt
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24770772
>>if (google.loader.ClientLocation)

probably evaluated to false
0
 

Author Comment

by:xenia27
ID: 24770796
How can I avoid this situation?
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 100 total points
ID: 24770885
>>How can I avoid this situation?

You need to check that it's not null first. See http://code.google.com/apis/ajax/documentation/#ClientLocation
0
 
LVL 92

Expert Comment

by:objects
ID: 24771063
as b0lsc0tt points out above (and you appear to have ignored) you're not loading the google js, or creating cl.
What you do in your html is completely independent to what you do in your java code.
ie. your html has nothing to do with your problem, you need to load the google js, and create cl in your *java* code if that where you want to use it.
Or make the call in your html (instead of java) and update the html dynamically.

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24771086
>>you're not loading the google js

That's not the case, it is being loaded, or an attempt is being made.

But don't you need a key as part of the query string?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24771098
There's absolutely no guarantee that ClientLocation will be valid, even when the js is loaded in the most ideal way, as described in the link i posted
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 24773632
Java isn't my expertise so may be it does have a way to run Javascript as a browser would and get and results or responses.  I do know a key is a required part of the request to Google's API.  Let me know if you need info on how to get it.
This actually brings us to a possible issue.  Even if Java provides a way to do it the key is tied to a domain.  Although the key can also work for "localhost" test it won't work from just anywhere.  This may be an issue that will cause your efforts to not work but I don't know enough about how Java would use the script to know for sure.
Let me know if you have a question or how this helps.
bol
0
 
LVL 92

Expert Comment

by:objects
ID: 24775528
b0lsc0tt,

your initial analysis of the cause of the problem was correct :)
0
 

Author Comment

by:xenia27
ID: 24782201
OK...here is what I try to do..
This is what I try to do...
When a user login on the web page, I can locate which city (even the exac location) of this user.  So the user can explorer the nearby product around this user.

I need to show the location and other products' location on a map; hence, I would love to have a google map on my web page.  Also, there will be more functions in Java program, then, I want to figure how I can get the information of the user's location.

Not sure whether this information is enough...

Still trying to work on the tips above...
0
 
LVL 92

Expert Comment

by:objects
ID: 24782229
Have you fixed up your java code to include all the javascript you need yet?
Why are you making the calls from java in the first place instead of directly from your html?
0
 
LVL 92

Expert Comment

by:objects
ID: 24782257
executing it in your java would not appear to be what you want.
0
 

Author Comment

by:xenia27
ID: 24782688
Nope, not yet...sorry for taking so long.  I would love to use google api in my html and get the values from my html to my java program.  Will this work?

Or, is there other ways to get values from my html to my java program?

0
 
LVL 92

Expert Comment

by:objects
ID: 24782709
>  would love to use google api in my html and get the values from my html to my java program.

you would just post them, but why do you need them in your java program?
0
 

Author Comment

by:xenia27
ID: 24782724
because I need to store these information into a database and when the particular user login again, the program will show these information again.  There are also some statistics calculation involved and email notifications, etc.
0
 

Author Comment

by:xenia27
ID: 24782737
I am confused that how I can start modify my programs now...
0
 
LVL 92

Expert Comment

by:objects
ID: 24782751
I'd suggest doing all your javascript calls in your html, and posting any details you need to store to your server. Running js with Java the way you are doing it will not work.
0
 

Author Comment

by:xenia27
ID: 24782787
how I can store the information so my server program can get them?  Is there any web site I can study?
0
 
LVL 92

Accepted Solution

by:
objects earned 200 total points
ID: 24782809
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Author Comment

by:xenia27
ID: 24782977
a little bit of confused still..but working on it now...
0
 

Author Comment

by:xenia27
ID: 24783071
so I should use html to get the values I want and use POST/GET in my java program to have the values from html?
0
 
LVL 92

Expert Comment

by:objects
ID: 24783135
no you would POST/GET them from the javascript by making a call to your server
0
 

Author Comment

by:xenia27
ID: 24783144
I see...let me try~~
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24783202
>>I am confused that how I can start modify my programs now...

The link i posted way back tells you all you need to know. You simply need to do this on the client in JavaScript and the link shows you how to use Ajax in this regard
0
 

Author Comment

by:xenia27
ID: 24783401
I tried to copy and paste the codes in the link aboved...and I kept having some error messages on the following line..
var mygetrequest=new ajaxRequest()
mygetrequest.onreadystatechange=function(){
 if (mygetrequest.readyState==4){
   document.getElementById("result").innerHTML=mygetrequest.responseText
 }
}  <-- error message here...said need an object

Any idea what's wrong?
0
 

Author Comment

by:xenia27
ID: 24783419
Never mind...I got what's wrong....still working on the example~
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24783426
Using a general API is not going to help you. Use the *specific* location API at the link i provided
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 24790786
In case there may be some confusion the AJAX code recently posted (see http:#a24783401) is not an API.  It isn't Google's either.  I am actually not really sure why it is needed.  You need these results in your Java code, right?  Have you tried just a basic test (i.e. a Google Search API) to see if your Java will get the response?  I wouldn't spend lots of time on details of this until you verify the basics will work.  Because of the way the Google API works I am afraid you won't be able to use it like you want.
This was mentioned earlier but you do know the ClientLocation results may not work and aren't very specific?  I just mention this because if you have to always get a location or need it to be more accurate than it is designed then you might as well stop now.  Google's Client Location does have some limitations.
Let me know if you have a question or need more info.
bol
0
 
LVL 92

Expert Comment

by:objects
ID: 24790817
the code used to call from java was never going to work as it was trying to access vars from the html
0
 

Author Comment

by:xenia27
ID: 24790936
OK...I quit my current program and start a new one using Javascript to get user's location as you guys suggested above.  Just delete the old program and start a new one since I was messed up my program already.

Is there any way that I can know the exact location without keyin by users?
0
 
LVL 54

Assisted Solution

by:b0lsc0tt
b0lsc0tt earned 200 total points
ID: 24790963
If you have a Google Maps API key set up try using the code below.  It uses Javascript and loads the Maps API to then get CurrentLocation.  It is the basic way to get the location (if the script can get it).  Keep in mind loading any of the Google APIs should make it so you can use the CurrentLocation code.  This uses Maps because it is a common use and simple example but you don't have to have a map on your page, etc.
Let me know if you have a question or how this works.  If you need help using it then let us know.
bol
p.s.  Don't forget to enter your key in the first script tag where you see "YOURKEYHERE".

<!--

 Copyright 2008 Google Inc. 

 Licensed under the Apache License, Version 2.0: 

 http://www.apache.org/licenses/LICENSE-2.0 

 -->

<html>

<head>

  <script type="text/javascript" src="http://www.google.com/jsapi?key=YOURKEYHERE"></script>

  <script>

  google.load("maps", "2", {callback: initialize});
 

  function initialize() {

    // Initialize default values

    var zoom = 3;

    var latlng = new google.maps.LatLng(37.4419, -100.1419);

    var location = "Showing default location for map.";
 

    // If ClientLocation was filled in by the loader, use that info instead

    if (google.loader.ClientLocation) {

      zoom = 13;

      latlng = new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);

      location = "Showing IP-based location: <b>" + getFormattedLocation() + "</b>";

    } 

   

    document.getElementById("location").innerHTML = location;

    var map = new google.maps.Map2(document.getElementById('map'));

    map.setCenter(latlng, zoom);

    map.addControl(new GLargeMapControl());

    map.addControl(new GMapTypeControl());

  }
 

  function getFormattedLocation() {

    if (google.loader.ClientLocation.address.country_code == "US" &&

      google.loader.ClientLocation.address.region) {

      return google.loader.ClientLocation.address.city + ", " 

          + google.loader.ClientLocation.address.region.toUpperCase();

    } else {

      return  google.loader.ClientLocation.address.city + ", "

          + google.loader.ClientLocation.address.country_code;

    }

  }
 

</script>

</head>

<body>

<div style="width:500;height:300" id="map"></div>

<div id="location"></div>

</body>

</html>

Open in new window

0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 24790967
Oops ... instead of CurrentLocation it should probably be ClientLocation.  I think the point is still clear but don't want to confuse this.
bol
0
 

Author Comment

by:xenia27
ID: 24791026
to b0lsc0tt,
I copied and pasted your code aboved, and I got this error message...said "Line: 36  The object does not support this attribute or method" (I am not sure what exact this error message is in English)  And line 36 is line 8 in the code aboved.

what should I do?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<!--

 Copyright 2008 Google Inc. 

 Licensed under the Apache License, Version 2.0: 

 http://www.apache.org/licenses/LICENSE-2.0 

 -->
 

<!-- The HTML 4.01 Transitional DOCTYPE declaration-->

<!-- above set at the top of the file will set     -->

<!-- the browser's rendering engine into           -->

<!-- "Quirks Mode". Replacing this declaration     -->

<!-- with a "Standards Mode" doctype is supported, -->

<!-- but may lead to some differences in layout.   -->
 

<html>

  <head>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
 

    <!--                                                               -->

    <!-- Consider inlining CSS to reduce the number of requested files -->

    <!--                                                               -->

    <link type="text/css" rel="stylesheet" href="XeniaNet.css">
 

    <!--                                           -->

    <!-- Any title is fine                         -->

    <!--                                           -->

    <title>Web Application Starter Project</title>

    

    <!--                                           -->

    <!-- This script loads your compiled module.   -->

    <!-- If you add any GWT meta tags, they must   -->

    <!-- be added before this line.                -->

    <!--                                           -->

    <script type="text/javascript" language="javascript" src="xenianet/xenianet.nocache.js"></script>

    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=true_or_false&amp;key=ABQIAAAAfY2iSWaI4XX7aNUo-orecBQqqM2Hu6GCM5KAICnzfaDmWdVsMBT6njvj6tjPmPnRX0ayG5_cz81O0w" type="text/javascript"></script>

    <script>

    	google.load("maps", "2", {callback: initialize});

    	function initialize() {

    		// Initialize default values

    		var zoom = 3;

    		var latlng = new google.maps.LatLng(37.4419, -100.1419);

    		var location = "Showing default location for map.";

    		 

    		// If ClientLocation was filled in by the loader, use that info instead

    		if (google.loader.ClientLocation) {

    			zoom = 13;

    		    latlng = new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);

    		    location = "Showing IP-based location: <b>" + getFormattedLocation() + "</b>";

    		} 

    		   

    		document.getElementById("location").innerHTML = location;

    		var map = new google.maps.Map2(document.getElementById('map'));

    		map.setCenter(latlng, zoom);

    		map.addControl(new GLargeMapControl());

    		map.addControl(new GMapTypeControl());

    	}

Open in new window

0
 

Author Comment

by:xenia27
ID: 24791055
now I removed the original html and copied your code and I got error message on line 4 said "must have '}'"
0
 

Author Comment

by:xenia27
ID: 24791107
ok..I figured out what's wrong...need this line <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> in my <head> section.
0
 

Author Comment

by:xenia27
ID: 24791114
so now I need to use POST/GET to communicate with my server program (in java)?
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 24791167
So does the page I provided work now just as an html page opened up in your browser?  Make sure you are testing it from your domain or as a "localhost" site.  If it does work then great.  Let me know if you need anything else as far as an html page that will do this.
>> so now I need to use POST/GET to communicate with my server program (in java)? <<
Isn't that back to what you decide to drop because it wasn't going to work?  Don't really understand what you mean and it seems like that is a line you said earlier about stuff you now know won't give the result you wanted.  Let me know if you think I have misread this.  Also if you are asking for help with that then please be more specific.  The sentence seems like a statement except it ends with a question mark.  I am not real sure what the question is.
bol
0
 
LVL 92

Expert Comment

by:objects
ID: 24791201
> Isn't that back to what you decide to drop because it wasn't going to work?

no, the original approach was trying to access the js from the java code.
you need to do it the other way round, ie your js call the server
0
 

Author Comment

by:xenia27
ID: 24791216
to b0lsc0tt,
the html works...now i need to move on to the next step...Thanks!!!

to objects,
what do you mean by the other way?  so calling my server from my js means using POST and GET?  Just wanna make sure before I move on..
0
 
LVL 92

Expert Comment

by:objects
ID: 24791223
> so calling my server from my js means using POST and GET?  

yes
0
 

Author Comment

by:xenia27
ID: 24791248
ok...thanks everyone~~~~
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24792513
xenia27, why did you mark http:#24782809 as the accepted answer? It's not relevant to your requirement and is an approach you correctly rejected ...
0
 

Author Comment

by:xenia27
ID: 24792538
mMmm...it helps me how to communicate with my server program (Java)...that's why I accepted that answer.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now