Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 362
  • Last Modified:

User Current Location

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
xenia27
Asked:
xenia27
  • 21
  • 11
  • 8
  • +2
3 Solutions
 
CEHJCommented:
>>So, I tried to call through Java

How? Please post code
0
 
fsze88Commented:
I need to store the information of user's location?
could you try store user's information into cookies?
0
 
xenia27Author Commented:
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
xenia27Author Commented:
What's wrong with my code?

Cookie?  Which one is easiest one?
0
 
b0lsc0ttCommented:
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
 
CEHJCommented:
>>if (google.loader.ClientLocation)

probably evaluated to false
0
 
xenia27Author Commented:
How can I avoid this situation?
0
 
CEHJCommented:
>>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
 
objectsCommented:
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
 
CEHJCommented:
>>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
 
CEHJCommented:
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
 
b0lsc0ttCommented:
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
 
objectsCommented:
b0lsc0tt,

your initial analysis of the cause of the problem was correct :)
0
 
xenia27Author Commented:
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
 
objectsCommented:
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
 
objectsCommented:
executing it in your java would not appear to be what you want.
0
 
xenia27Author Commented:
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
 
objectsCommented:
>  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
 
xenia27Author Commented:
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
 
xenia27Author Commented:
I am confused that how I can start modify my programs now...
0
 
objectsCommented:
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
 
xenia27Author Commented:
how I can store the information so my server program can get them?  Is there any web site I can study?
0
 
objectsCommented:
0
 
xenia27Author Commented:
a little bit of confused still..but working on it now...
0
 
xenia27Author Commented:
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
 
objectsCommented:
no you would POST/GET them from the javascript by making a call to your server
0
 
xenia27Author Commented:
I see...let me try~~
0
 
CEHJCommented:
>>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
 
xenia27Author Commented:
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
 
xenia27Author Commented:
Never mind...I got what's wrong....still working on the example~
0
 
CEHJCommented:
Using a general API is not going to help you. Use the *specific* location API at the link i provided
0
 
b0lsc0ttCommented:
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
 
objectsCommented:
the code used to call from java was never going to work as it was trying to access vars from the html
0
 
xenia27Author Commented:
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
 
b0lsc0ttCommented:
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
 
b0lsc0ttCommented:
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
 
xenia27Author Commented:
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
 
xenia27Author Commented:
now I removed the original html and copied your code and I got error message on line 4 said "must have '}'"
0
 
xenia27Author Commented:
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
 
xenia27Author Commented:
so now I need to use POST/GET to communicate with my server program (in java)?
0
 
b0lsc0ttCommented:
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
 
objectsCommented:
> 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
 
xenia27Author Commented:
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
 
objectsCommented:
> so calling my server from my js means using POST and GET?  

yes
0
 
xenia27Author Commented:
ok...thanks everyone~~~~
0
 
CEHJCommented:
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
 
xenia27Author Commented:
mMmm...it helps me how to communicate with my server program (Java)...that's why I accepted that answer.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 21
  • 11
  • 8
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now