How can I insert the result into a form fiel? - geolocation

The piece of code bellow (we all know the origin) helps you get geo coordinates.
The result is being displayed in the div called result.
What I need, is for the result to be displayed in a form field so that I can save it to my database, instead of manually typing it.
Thanks
<!DOCTYPE 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: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
var map, infoWindow;
function initMap() {
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);
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
The piece of code below (we all know the origin) helps you get geo coordinates.
The result is being displayed in the div called result.
What I need, is for the result to be displayed in a form field so that I can save it to my database, instead of manually typing it.
Thanks

Related

Snazzy Maps in Rails Application

I set up a nice map in my rails application. Everything is working fine but I cannot style the map with SnazzyMaps.
Here is my map.js file:
import GMaps from 'gmaps/gmaps.js';
const mapElement = document.getElementById('map');
if (mapElement) { // don't try to build a map if there's no div#map to inject in
const map = new GMaps({ el: '#map', lat: 0, lng: 0 });
const markers = JSON.parse(mapElement.dataset.markers);
const mapMarkers = map.addMarkers(markers);
mapMarkers.forEach((marker, index) => {
marker.addListener('click', () => {
// map.setCenter(markers[index]);
markers[index].infoWindow.open(map, marker);
})
});
if (markers.length === 0) {
map.setZoom(2);
} else if (markers.length === 1) {
map.setCenter(markers[0].lat, markers[0].lng);
map.setZoom(14);
} else {
map.fitLatLngBounds(markers);
}
}
import { autocomplete } from '../components/autocomplete';
// [...]
autocomplete();
On SnazzyMaps they give the following example. My question is, where shall I insert which part of this code in my own file. Been trying it for a while now but cannot make it work. Here is SnazzyMaps example:
<!DOCTYPE html>
<html>
<head>
<title>Snazzy Maps Super Simple Example</title>
<style type="text/css">
/* Set a size for our map container, the Google Map will take up 100% of this container */
#map {
width: 750px;
height: 500px;
}
</style>
<!--
You need to include this script tag on any page that has a Google Map.
The following script tag will work when opening this example locally on your computer.
But if you use this on a localhost server or a live website you will need to include an API key.
Sign up for one here (it's free for small usage):
https://developers.google.com/maps/documentation/javascript/tutorial#api_key
After you sign up, use the following script tag with YOUR_GOOGLE_API_KEY replaced with your actual key.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_API_KEY"></script>
-->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);
function init() {
// Basic options for a simple Google Map
// For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
var mapOptions = {
// How zoomed in you want the map to start at (always required)
zoom: 11,
// The latitude and longitude to center the map (always required)
center: new google.maps.LatLng(40.6700, -73.9400), // New York
// How you would like to style the map.
// This is where you would paste any style found on Snazzy Maps.
styles: [{"featureType":"all","elementType":"geometry.fill","stylers":[{"weight":"2.00"}]},{"featureType":"all","elementType":"geometry.stroke","stylers":[{"color":"#9c9c9c"}]},{"featureType":"all","elementType":"labels.text","stylers":[{"visibility":"on"}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2f2f2"}]},{"featureType":"landscape","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":-100},{"lightness":45}]},{"featureType":"road","elementType":"geometry.fill","stylers":[{"color":"#eeeeee"}]},{"featureType":"road","elementType":"labels.text.fill","stylers":[{"color":"#7b7b7b"}]},{"featureType":"road","elementType":"labels.text.stroke","stylers":[{"color":"#ffffff"}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#46bcec"},{"visibility":"on"}]},{"featureType":"water","elementType":"geometry.fill","stylers":[{"color":"#c8d7d4"}]},{"featureType":"water","elementType":"labels.text.fill","stylers":[{"color":"#070707"}]},{"featureType":"water","elementType":"labels.text.stroke","stylers":[{"color":"#ffffff"}]}]
};
// Get the HTML DOM element that will contain your map
// We are using a div with id="map" seen below in the <body>
var mapElement = document.getElementById('map');
// Create the Google Map using our element and options defined above
var map = new google.maps.Map(mapElement, mapOptions);
// Let's also add a marker while we're at it
var marker = new google.maps.Marker({
position: new google.maps.LatLng(40.6700, -73.9400),
map: map,
title: 'Snazzy!'
});
}
</script>
</head>
<body>
<h1>Snazzy Maps Super Simple Example</h1>
<h2>WY</h2>
<!-- The element that will contain our Google Map. This is used in both the Javascript and CSS above. -->
<div id="map"></div>
</body>
</html>
To set the style using Gmaps library, you need to define the styles and then set it to the current map as below:
const map = new GMaps({ el: '#map', lat: 0, lng: 0 });
var styles = [
{
stylers: [
{ hue: "#00ffe6" },
{ saturation: -20 }
]
}, {
featureType: "road",
elementType: "geometry",
stylers: [
{ lightness: 100 },
{ visibility: "simplified" }
]
}, {
featureType: "road",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
}
];
map.addStyle({
styledMapName:"Styled Map",
styles: styles,
mapTypeId: "map_style"
});
map.setStyle("map_style");
Reference:
https://github.com/hpneo/gmaps/blob/master/examples/styled_maps.html

ArcGIS 3.x to 4.x Migration

I was using ArcGIS JS API 3.10 and have a Github
repository to display GeoJSON data on a map but now I have to upgrade to
4.9 version I read 3.x to 4.x migration document published by ESRI and apply he changes like link location etc. but it’s not working anymore.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=7,IE=9">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>ArcGIS GeoJSON Layer</title>
<!-- ArcGIS API for JavaScript CSS-->
<link rel="stylesheet" href="https://js.arcgis.com/4.9/esri/css/main.css">
#*<link rel="stylesheet" href="//js.arcgis.com/3.9/js/esri/css/esri.css">*#
<!-- Web Framework CSS - Bootstrap (getbootstrap.com) and Bootstrap-map-js (github.com/esri/bootstrap-map-js) -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="//esri.github.io/bootstrap-map-js/src/css/bootstrapmap.css">
<style>
html, body, #mapDiv {
height: 500px;
width: 100%;
}
</style>
<script src="https://js.arcgis.com/4.9/"></script>
<!-- ArcGIS API for JavaScript library references -->
#*<script src="//js.arcgis.com/3.10"></script>*#
<!-- Terraformer reference -->
<script src="/vendor/terraformer/terraformer.min.js"></script>
<script src="/vendor/terraformer-arcgis-parser/terraformer-arcgis-parser.min.js"></script>
<script>
require(["esri/Map",
"/Scripts/Refine.js",
"dojo/on",
"dojo/dom",
"dojo/domReady!"],
function (Map, GeoJsonLayer, on, dom) {
// Create map
var map = new Map("mapDiv", {
basemap: "gray",
center: [-122.5, 45.5],
zoom: 5
});
map.on("load", function () {
addGeoJsonLayer("http://113.197.55.251/api/punjab");
});
// Add the layer
function addGeoJsonLayer(url) {
// Create the layer
var geoJsonLayer = new GeoJsonLayer({
url: url
});
// Zoom to layer
geoJsonLayer.on("update-end", function (e) {
map.setExtent(e.target.extent.expand(1.2));
});
// Add to map
map.add(geoJsonLayer);
}
});
</script>
</head>
<body>
<div id="mapDiv"></div>
</body>
</html>
In ArcGIS 4.9 you have to use a MapView like below:
For the conversion between GeoJson and EsriJson, I suggest you the arcgis-to-geojson-utils library
Import the library in your html:
<script src="https://unpkg.com/#esri/arcgis-to-geojson-utils"></script>
javascript:
require([
"esri/Map",
"esri/views/MapView",
"esri/Graphic",
"esri/layers/FeatureLayer",
"esri/layers/support/Field",
"dojo/on",
"dojo/dom",
"dojo/domReady!"],
function (Map, MapView, Graphic, FeatureLayer, Field, on, dom) {
// Create mapView and map
var mapView = new MapView({
container: mapDiv,
map: new Map({
basemap: "gray"
}),
center: [-122.5, 45.5],
zoom: 5
}).when(function(mapView) {
makeRequest("http://113.197.55.251/api/punjab", function(response) {
createLayerFromGeoJSON(response, mapView);
});
});
// Request the geojson data using XmlHttpRequest
function makeRequest(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(JSON.parse(xhr.response));
}
};
xhr.onerror = function(error) {
throw error;
}
xhr.send();
};
// Create the layer from the geojson data
function createLayerFromGeoJSON(geojson, mapView) {
// Convert geojson to esriJson using arcgis-to-geojson-utils library
var esriJson = ArcgisToGeojsonUtils.geojsonToArcGIS(geojson);
// Create an array of graphics from the esriJson
var graphics = esriJson.map(function(feature, i) {
return new Graphic({
geometry: {
type: "polygon",
rings: feature.geometry.rings
},
attributes: {
ObjectID: i,
Name: feature.attributes.Name
}
});
});
// Create a FeatureLayer from the graphics
var layer = new FeatureLayer({
title: "My feature layer",
source: graphics, // autocast as an array of esri/Graphic
geometryType: "polygon",
fields: [
new Field({
name: "ObjectID",
alias: "ObjectID",
type: "oid"
}),
new Field({
name: "Name",
alias: "Name",
type: "string"
}),
],
objectIdField: "ObjectID", // This must be defined when creating a layer from Graphics
renderer: {
type: "simple", // autocasts as new SimpleRenderer()
symbol: {
type: "simple-fill", // autocasts as new SimpleFillSymbol()
color: {r: 200, g: 200, b: 200, a: 0.5},
outline: { // autocasts as new SimpleLineSymbol()
width: 0.5,
color: "black"
}
}
}
});
mapView.map.add(layer);
return layer;
};
});
In ArcGis Js 4.x version you have to also declare a view constructor (MapView for 2D or SceneView for 3D). Here is a guide on how to set up 2D view: https://developers.arcgis.com/javascript/latest/sample-code/intro-mapview/index.html
Another way to add Json file is to convert your existing your json file to an esri json format, like in this guide: https://developers.arcgis.com/javascript/latest/sample-code/sandbox/index.html?sample=layers-featurelayer-collection.
Since I don't know your json file attributes I can't really provide a working sample, but its really simple.

iOS 7 UIWebView memory leak with Google Maps Javascript API

I have an iOS application which displays a map using the Google Maps Javascript API in a UIWebView. It seems that in iOS 7.0, something has changed in the UIWebView implementation that is causing map objects to not be released when there are no longer any references.
Using the XCode memory profiler, I see a 7-20 MB increase in RAM each time a map is created. Removing the map, and clearing references to it does not decrease the memory usage. Memory warnings do not seem to trigger Javascript garbage collection. When running the code on a physical device, the application logs memory warnings and inevitably will crash.
Here is some simplified Javascript which demonstrates the problem:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title></title>
<style type="text/css" media="screen">
body { padding-top: 20px;}
#container { width:100%; height:200px; }
#container > div { height: 100%; width: 100%; }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" charset="utf-8">
var domEl;
function createMap() {
var container = document.getElementById( 'container' );
// Create fresh dom element
//
if( domEl ) {
container.removeChild( domEl );
console.log('removed old dom element');
}
domEl = document.createElement( 'div' );
container.appendChild( domEl );
// Create map
//
var mapOptions = {
center: new google.maps.LatLng( -34.397, 150.644 ),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
new google.maps.Map( domEl, mapOptions );
return false;
}
</script>
</head>
<body>
Create map
<div id="container"></div>
</body>
</html>
I've also posted a complete XCode project on GitHub.
Has anyone seen this before? Can someone suggest a fix or workaround? In this case I have to use the Google Maps API; a native solution isn't an option.

InfoWindow contents spilling out using dynamic template?

Can anyone tell my why the contents of my InfoWindows are spilling out? When I view the InfoWindows in the Fusion Table UI, they all pop up and resize themselves correctly:
https://www.google.com/fusiontables/embedviz?q=select+col7+from+15wosKAeHC0gcpU_N6UPbxPL09RrEBKlQNEaCmnU&viz=MAP&h=false&lat=34.199813229302734&lng=-111.2955847411987&t=1&z=8&l=col7&y=2&tmplt=2
But when I try to use the html code to create a webpage, some (not all) of the InfoWindow contents spill out:
<!DOCTYPE html>
<html>
<head>
<title>CaveCreek - Google Fusion Tables</title>
<style type="text/css">
html, body, #googft-mapCanvas {
height: 300px;
margin: 0;
padding: 0;
width: 500px;
}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
google.maps.visualRefresh = true;
var map = new google.maps.Map(document.getElementById('googft-mapCanvas'), {
center: new google.maps.LatLng(34.199813229302734, -111.2955847411987),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('googft-legend'));
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "col7",
from: "15wosKAeHC0gcpU_N6UPbxPL09RrEBKlQNEaCmnU",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googft-mapCanvas"></div>
</body>
</html>
My dynamic template InfoWindow code looks like:
{template .contents}
<div>
<div style="align: center">
<b>{$data.value.Stream}</b>
</div>
{if $data.value.y2012}
2012-{/if}
{if $data.value.y2012a}
2012a-{/if}
...
</div>
{/template}
I have tried to add height and width to the div tag for the InfoWindow in the template but that still doesn't seem to work.
Remove the visualRefresh, that is causing the infoWindow size to be calculated incorrectly.
google.maps.visualRefresh = true;
Note that the Google Maps visual refresh is going to be the default soon, so removing it is not a long-term solution.
If you set the height of the div and add overflow-y: scroll you should get a scrollbar on your content; does that not happen? One of the examples in the dynamic template help is setting the height differently based on fields being there or not, so that might help.

jQuery Mobile - Google navigation - Directions Service - Current position identification

I have a JQuery Mobile website that people use with their Android device.
(This website mainly deals with clients information.)
I've been looking to integrate a "GET DIRECTION" feature.
I was wondering if it's possible to open Google Navigation app (because it can be used as a GPS, voice navigation) with the current location and one client's address through JQM ?
If not, does anyone has any suggestion?
The official W3C site informs about the W3C Geolocation working group and the milestones that have been set.
You can find here a fresh (May 2012) W3C draft proposal for the Geolocation API.
Below you can find a sample working example that I created. The code finds the current position and provides a direction service. There is a textbox where you can write the target destination and a button which "Get Directions". When you click the button a list at the end of the page is filled with the directions.
You can modify it in order to fit your needs. Furthermore you can find more information about the directions service in the Google Map JavaScript API Directions Service.
<!doctype html>
<html lang="en">
<head>
<title>jQuery mobile with Google maps</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"> </script>
<script type="text/javascript">
var map;
var currentPosition;
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
function initialize(lat, lon)
{
currentPosition = new google.maps.LatLng(lat, lon);
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 15,
center: currentPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
//directionsDisplay.setPanel($("#instructions-content"));
var currentPositionMarker = new google.maps.Marker({
position: currentPosition,
map: map,
title: "Current position"
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(currentPositionMarker, 'click', function() {
infowindow.setContent("Current position: latitude: " + lat +" longitude: " + lon);
infowindow.open(map, currentPositionMarker);
});
}
function locError(error)
{
alert("The position or the map could not be loaded.");
}
function locSuccess(position)
{
initialize(position.coords.latitude, position.coords.longitude);
}
$(document).ready(function()
{
navigator.geolocation.getCurrentPosition(locSuccess, locError);
$("#directions-button").click(function(){
var targetDestination = $("#target-dest").val();
if (currentPosition && currentPosition != '' && targetDestination && targetDestination != '')
{
var request = {
origin:currentPosition,
destination:targetDestination,
travelMode: google.maps.DirectionsTravelMode["DRIVING"]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setPanel(document.getElementById("instructions-content"));
directionsDisplay.setDirections(response);
// For debuging reasons uncomment
/*
var myRoute = response.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
alert(myRoute.steps[i].instructions);
}*/
}
});
}
else
{
alert("The target destination is empty or the current position could not be located.");
}
});
});
</script>
</head>
<body>
<div id="basic-map" data-role="page">
<div data-role="header">
<h1><a data-ajax="false" href="/">jQuery mobile with Google maps v3</a> examples</h1>
</div>
<div data-role="content">
<div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:350px;"></div>
</div>
<div data-role="fieldcontain">
<label for="name">Target Destination:</label>
<input type="text" name="target-dest" id="target-dest" value="" />
</div>
Get Directions
<div data-role="collapsible" id="instructions-container">
<h3>Instructions</h3>
<p><div id="instructions-content"></div></p>
</div>
</div>
</div>
</body>
</html>
Put the HTML code in a file map.html and open it directly with Mozilla Firefox (in case you don't want to put it on a server and test it). Otherwise put the file on a server and open it with any browser you want.
Initially you will be asked whether you want to share your current location. After you press the Share button you will see a map with a marker showing your current position. If you click the marker you will see you latitude and longitude.
I hope this helps.

Resources