Getting Latitude and longitude from google maps [duplicate] - java

This question already has an answer here:
Getting Latitude from Geocode Object
(1 answer)
Closed 8 years ago.
My task was to generate Latitude and longitude when a user enters the address and store it in database.I looked around and Google Maps API has given the implementation for this. But the issue is it shows address on the map but not the coordinates.I am not very familiar with the Maps API but is there any way to generate the coordinates and display in the input feild.
Thanks.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Geocoding service</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map-canvas"></div>
</body>
</html>

Got the answer. All I had to do was get the lat and lon from result.
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();

Related

Updating product with shoppy api

I am using the shoppy api, and I need to update a product using the api, I am trying to update the account list, I am able to update the title/desc, I am not able to update the account list, It says on here I need to send an array, and I did that but the shoppy server dies, this is my code, I am using unirest for the post requestion.
Map<String, String> accs = new HashMap<>();
accs.put("username", "password");
String response = Unirest.post("https://shoppy.gg/api/v1/products/xxx").queryString("accounts", accs).headers(headers).asString().getBody();
printing response returns an error page, but when I just update the title, it says my update was successful, so I am not sure what I am doing wrong here.
This is the print from response
<!DOCTYPE html>
<html>
<head>
<title>Be right back.</title>
<link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">
<style>
html, body {
height: 100%;
}
body {
margin: 0;
padding: 0;
width: 100%;
color: #B0BEC5;
display: table;
font-weight: 100;
font-family: 'Lato', sans-serif;
}
.container {
text-align: center;
display: table-cell;
vertical-align: middle;
}
.content {
text-align: center;
display: inline-block;
}
.title {
font-size: 72px;
margin-bottom: 40px;
font-weight: 200;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
<div class="title">Be right back.</div>
</div>
</div>
</body>
</html>
I believe the error is in how you're passing accs to the .queryString() method.
Take a look at the Unirest documentation for how you pass arrays and maps to queryString() from http://kong.github.io/unirest-java/#requests :
To pass an array or a map:
Unirest.get("http://httpbin.org")
.queryString("fruit", Arrays.asList("apple", "orange"))
.queryString(ImmutableMap.of("droid", "R2D2", "beatle", "Ringo"))
.asString();
// Results in "http://httpbin.org?fruit=apple&fruit=orange&droid=R2D2&beatle=Ringo"
Based on the example above, it looks like you're passing in your accs map as if it were an array, when it is actually a Map. If you want to pass an array, try this:
String response = Unirest.post("https://shoppy.gg/api/v1/products/xxx")
.queryString("accounts", Arrays.asList(accs))
.headers(headers)
.asString()
.getBody();

Strange chracters in google maps API using java WebView

EDIT:
I think I found the problem, I test the application in a window with java 7 and runs fine, no weird symbols and run the application on two different macs with java 8 and fail. I don't believe is the version because java it's supposed to run on any platform equally any theory.
RE:EDIT:
Is the OS!!!!! I just check, in a Windows with java 8 and worked, has to do with the encoding what can I do?? :'(. (I use macOS)
Maybe is only the JavaFX version and could save an old version of JavaFX in the app but don't know how to do that help, please.
END EDIT
I've made a desktop java application using WebView in JavaFX and make my own HTML page and everything worked fine, but suddenly the characters fails and I don't think is the HTML because I put an H1 and look fine but the google maps don't.
The HTML works fine in a browser but fails in java!.
Also, I erase the cookies.
Here is a screenshot
Here is the HTML most copy paste from google api:
<!DOCTYPE html>
<html>
<head>
<meta >
<title> "Vista de Clientes" </title>
<style>
#map {
height: 100%;
}
html, body {
font-family: sans-serif;
height: 100%;
margin: 0;
padding: 0;
}
.controls {
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 300px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#target {
width: 345px;
}
</style>
</head>
<body>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<h1> hola </h1>
<div id="map"></div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=APIKEYISGOOD&libraries=places"></script>
<script>
// object for the stores
var GreenCircle = {
path: google.maps.SymbolPath.CIRCLE,
fillColor: 'Lime',
fillOpacity: 1,
scale: 10,
strokeColor: 'green',
strokeWeight: 1
};
// google map instance
var map;
var markers = [];
// function for the initialization
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 21.8857199, lng: -102.3613399}
});
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location,
draggable: true
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
initMap();
function setMarker(latvar, lngvar, labels){
var marker = new google.maps.Marker({
position: { lat: latvar, lng: lngvar},
map: map,
label: labels || "",
tittle: labels,
icon: GreenCircle
});
}
function setSelfMarker(Geojson)
{
map.data.addGeoJson( JSON.parse(Geojson) );
}
function setPosition(lat, lng)
{
map.setCenter(new google.maps.LatLng( lat, lng ) );
}
</script>
</body>
</html>
I load the code using:
String webPage = this.getFileSrc("VistaClientes.html");
webEngine.loadContent( webPage);
Is a string containing the full html.
The problem here is that there is a bug in the JavaFX webview on Mac. It tries to load some fonts locally and is disallowed. You can workaround this for Google maps by adding the following CSS directive to your <style> tag.
.gm-style-mtc > div, .gm-style > div, .gm-style-cc > div, .gm-style {font-family:sans-serif !important;}

<jsp:include> not respecting position styles of the jsp included

I have an index.jsp which includes header.jsp by <jsp:include>. The doc header.jsp has 2 elements that I've positioned at the bottom right corner. If I execute the header file as .html, both elements are positioned correctly, but when I execute index.jsp both items are at the top right corner ignoring just the position style because, as you can see, the loginButton and messageLabel divs still have the rest of their styles.
This is what I see if I execute the header like an html (I see it properly):
And this is what I see if I execute the index.jsp in my local server:
The index.jsp:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<jsp:include page="header.jsp" />
<h1>Hello World!</h1>
</body>
</html>
The header.jsp:
<link rel="stylesheet" type="text/css" href="Resources/Styles/headerStyles.css" />
<header id="header">
<label id="messageLabel">User not registered</label>
<div id="loginButton">
Login
</div>
</header>
The headerStyles.css:
#header {
background-color: yellow;
width: 100%;
height: 92px;
}
#loginButton {
position: absolute;
right: 8;
top: 60;
background-color: darkorange;
height: 40px;
width: 80px;
text-align: center;
line-height: 40px;
font-weight: bolder;
font-size: 15pt;
}
#messageLabel {
position: absolute;
right: 100;
top: 70;
}
OK, I got it. You only have to specify the unit of measurement in attributes right and top like this:
#header {
background-color: yellow;
width: 100%;
height: 92px;
}
#loginButton {
position: absolute;
right: 8px;
top: 60px;
background-color: darkorange;
height: 40px;
width: 80px;
text-align: center;
line-height: 40px;
font-weight: bolder;
font-size: 15pt;
}
#messageLabel {
position: absolute;
right: 100px;
top: 70px;
}
It seems measures must be followed by their proper unit of measurement correctly specified. It's quite strict.

Extract information from JavaScript function in terms of country, state, city and locality which directly gives full address in Spring mvc

I have to add country, state, city,and remaining address if it contains. But I'm not proficient in using Google API along with JavaScript. I'm using ready made JavaScript function which gives full address on textbox after using autocomplete.
I don't know how to take or extract the country, state, city from full address.
I am giving my code:
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
.controls {
margin-top: 16px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
background-color: #fff;
padding: 0 11px 0 13px;
width: 400px;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
text-overflow: ellipsis;
}
#pac-input:focus {
border-color: #4d90fe;
margin-left: -1px;
padding-left: 14px; /* Regular padding-left + 1. */
width: 401px;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script>
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
var types = document.getElementById('type-selector');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
// alert("here is your addresss :" address);
infowindow.open(map, marker);
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
google.maps.event.addDomListener(radioButton, 'click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<input id="pac-input" class="controls" type="text"
placeholder="Enter a location">
<div id="type-selector" class="controls">
<input type="radio" name="type" id="changetype-all" checked="checked">
<label for="changetype-all">All</label>
<input type="radio" name="type" id="changetype-establishment">
<label for="changetype-establishment">Establishments</label>
<input type="radio" name="type" id="changetype-geocode">
<label for="changetype-geocode">Geocodes</label>
</div>
<div id="map-canvas"></div>
</body>
</html>
Thanks for giving reply. From this output on search locality I want to extract individual county ,state,city and locality and use in Spring MVC class pojo.
Below is the section of code (from what you gave) that you should be interested in.
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
Essentially, what this part does, is it initializes the address variable (empty initially). Then, if the place object (presumably returned from Google) is not empty and contains components, if fills the address with all the separate components from place.
The above code implies that the place object returned by Google provides you with three (3) components specifically: those at index positions 0, 1, and 2.
You will have to figure out if these components, on their own, give you the separated information you need. To check that, try updating with the following code (notice the FOR loop I added):
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
for (var i = 0; i < place.address_components.length; i++)
{
console.log('Component at index ' + i
+ ' is: ' + place.address_components[i].short_name;
}
}
Run the updated code and check your console (available with Chrome) -- it will let you know which components were returned by Google, with their index number. Use that knowledge to achieve your goal.

Sending push notfications to multiple devices using this code (PHP)

I'm new to GCM / Java, I'm experienced in php, but only mysql.
I found this tutorial:
http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
It was very useful, and I got it to work. My only problem is that this code is for sending to one device at a time.
I tryed to edit it so it sends to multiple devices using one form & one submit button, but without a success.
This code gets from Java (Client) Info and puts it in a mysql database using php (Server).
It also registers the GCM registration id of the device in the mysql DB,
and than you can send notifications by id to the device using the id's GCM reg id.
Here is the index.php where you fill in the form:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
<style type="text/css">
.container{
width: 950px;
margin: 0 auto;
padding: 0;
}
h1{
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 24px;
color: #777;
}
div.clear{
clear: both;
}
ul.devices{
margin: 0;
padding: 0;
}
ul.devices li{
float: left;
list-style: none;
border: 1px solid #dedede;
padding: 10px;
margin: 0 15px 25px 0;
border-radius: 3px;
-webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
-moz-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #555;
}
ul.devices li label, ul.devices li span{
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 12px;
font-style: normal;
font-variant: normal;
font-weight: bold;
color: #393939;
display: block;
float: left;
}
ul.devices li label{
height: 25px;
width: 50px;
}
ul.devices li textarea{
float: left;
resize: none;
}
ul.devices li .send_btn{
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#0096FF), to(#005DFF));
background: -webkit-linear-gradient(0% 0%, 0% 100%, from(#0096FF), to(#005DFF));
background: -moz-linear-gradient(center top, #0096FF, #005DFF);
background: linear-gradient(#0096FF, #005DFF);
text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3);
border-radius: 3px;
color: #fff;
}
</style>
</head>
<body>
<?php
include_once 'db_functions.php';
$db = new DB_Functions();
$users = $db->getAllUsers();
if ($users != false)
$no_of_users = mysql_num_rows($users);
else
$no_of_users = 0;
?>
<div class="container">
<h1>No of Devices Registered: <?php echo $no_of_users; ?></h1>
<hr/>
<ul class="devices">
<?php
if ($no_of_users > 0) {
?>
<?php
while ($row = mysql_fetch_array($users)) {
?>
<li>
<form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">
<label>Name: </label> <span><?php echo $row["name"] ?></span>
<div class="clear"></div>
<label>Email:</label> <span><?php echo $row["klas"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
</form>
</li>
<?php }
} else { ?>
<li>
No Users Registered Yet!
</li>
<?php } ?>
</ul>
</div>
</body>
</html>
It's using ajax to send it to GCM:
Send_message.php:
<?php
if (isset($_GET['regId']) && (isset($_GET["message"]))) {
$regId = $_GET['regId'];
$message = $_GET["message"];
include_once './GCM.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("price" => $message);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
}
?>
As you see, it gets everthing by id,
but I want to use one form, one submit button & one text field to send to multiple devices.
Would really appreciate it if someone could instruct me how to do it or give me some examples.
I don't know php, but GCM.php from the link you provided seems to already support sending push notifications to multiple devices :
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
You should simply pass to the send_notification function an array that contains multiple Registration IDs, and it would send notifications to all of them.

Categories

Resources