I'm trying to make an React app, that shows the distance between two points on a map.
I got it to work in Javascript and HTML, but i'm having trouble converting it to React (I'm new).
At first i got an error: 'google' is not defined. i fixed it by adding: const google = window.google;
Now i'm getting these errors:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!-- GOOGLE API -->
<script src="https://maps.googleapis.com/maps/api/js?key=MY_GOOGLE_MAPS_API_KEY&libraries=places"></script>
<!-- BOOTSTRAP -->
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"
></script>
</body>
</html>
App.js:
import logo from "./logo.svg";
import "./App.css";
import GoogleMapsApi from "./GoogleMapsApi";
function App() {
return (
<>
<GoogleMapsApi/>
</>
);
}
export default App;
GoogleMapsApi.js:
import React from "react";
import $ from "jquery";
const google = window.google;
const GoogleMapsApi = () => {
//set map options
// start pos
const myLatLng = { lat: 51.5, lng: -0.1 };
const mapOptions = {
center: myLatLng,
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
//create map
const map = new google.maps.Map(
document.getElementById("googleMap"),
mapOptions
);
//create a DirectionsService object to use the route method and get a result for our request
const directionsService = new google.maps.DirectionsService();
//create a DirectionsRenderer object which we will use to display the route
const directionsDisplay = new google.maps.DirectionsRenderer();
//bind the DirectionsRenderer to the map
directionsDisplay.setMap(map);
//define calcRoute function
function calcRoute() {
//create request
const request = {
origin: document.getElementById("from").value,
destination: document.getElementById("to").value,
travelMode: google.maps.TravelMode.DRIVING, //WALKING, BYCYCLING, TRANSIT
unitSystem: google.maps.UnitSystem.METRIC,
};
//pass the request to the route method
directionsService.route(request, function (result, status) {
if (status === google.maps.DirectionsStatus.OK) {
//Get distance and time
$("#output").html(
"<div class='alert-info'>From: " +
document.getElementById("from").value +
".<br />To: " +
document.getElementById("to").value +
".<br /> Driving distance: " +
result.routes[0].legs[0].distance.text +
".<br />Duration: " +
result.routes[0].legs[0].duration.text +
".</div>"
);
//display route
directionsDisplay.setDirections(result);
} else {
//delete route from map
directionsDisplay.setDirections({ routes: [] });
//center map in London
map.setCenter(myLatLng);
//show error message
$("#output").html(
"<div class='alert-danger'>Could not retrieve driving distance.</div>"
);
}
});
}
const x = document.getElementById("from");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
// Use this to show in app
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
document.getElementById("from").value =
position.coords.latitude + ", " + position.coords.longitude;
}
return (
<>
<div className="App">
<div class="jumbotron">
<div class="container-fluid">
<h1>Distance between cities App.</h1>
<p>Our app will help you calculate travelling distances.</p>
<form class="form-horizontal">
<div class="form-group">
<label for="from" class="col-xs-2 control-label">
From:
</label>
<div class="col-xs-10">
<input
type="text"
id="from"
placeholder="Origin"
class="form-control"
/>
</div>
</div>
<div class="form-group">
<label for="to" class="col-xs-2 control-label">
To:
</label>
<div class="col-xs-10">
<input
type="text"
id="to"
placeholder="Destination"
class="form-control"
/>
</div>
</div>
</form>
{/* GET LOCATION IN LAT AND LONG */}
<div class="col-xs-offset-2 col-xs-10">
{/* Get currnet */}
<button class="btn btn-info btn-lg" onClick={getLocation()}>
Try It
</button>
<p id="demo"></p>
</div>
<div class="col-xs-offset-2 col-xs-10">
<button class="btn btn-info btn-lg" onClick={calcRoute()}>
Submit
</button>
</div>
</div>
<div class="container-fluid">
<div id="googleMap"></div>
<div id="output"></div>
</div>
</div>
</div>
</>
);
};
export default GoogleMapsApi;
Foremost, I would consider using google-map-react instead of using window.google directly.
R.e. your specific error: I suspect your document.getElementById("googleMap") is returning null because <div id="googleMap"></div> won't have been rendered when the GoogleMapsApi component is initialized.
Review State and Lifecycle
, specifically:
The componentDidMount() method runs after the component output has been rendered to the DOM.
Inside componentDidMount() your document.getElementById("googleMap") should return a non-null value.
I also recommend looking at the code for google-map-react to see how it is implemented there.
Related
I found this code on mapbox page. I need those coordinates to pass into html form. What is the best way to do this. I have tried using getdocumentbyId but for some reason I have more errors in that, and it doesn't work at all.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.css" rel="stylesheet" />
</head>
<body>
<div id="map"></div>
<pre id="coordinates" class="coordinates"></pre>
<script>
mapboxgl.accessToken = 'my.tkn';
var coordinates = document.getElementById('coordinates');
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [18.38 , 43.848],
zoom: 15
});
var marker = new mapboxgl.Marker({
draggable: true
})
.setLngLat([18.38 , 43.848])
.addTo(map);
function onDragEnd() {
var lngLat = marker.getLngLat();
coordinates.style.display = 'block';
coordinates.innerHTML =
'Longitude: ' + lngLat.lng + '<br />Latitude: ' + lngLat.lat;
}
marker.on('dragend', onDragEnd);
</script>
<form>
<input type="text" id="hvalue" name="hvalue">
<input type="text" id="wvalue" name="wvalue">
</form>
</body>
</html>
if i understood correct this is what you want to get:
-i relocate the script under the form.
-i added getElementById().value =
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.css" rel="stylesheet" />
</head>
<body>
<div id="map"></div>
<pre id="coordinates" class="coordinates"></pre>
<form>
<input type="text" id="hvalue" name="hvalue">
<input type="text" id="wvalue" name="wvalue">
</form>
<script>
mapboxgl.accessToken = 'my.tkn';
var coordinates = document.getElementById('coordinates');
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [18.38 , 43.848],
zoom: 15
});
var marker = new mapboxgl.Marker({
draggable: true
})
.setLngLat([18.38 , 43.848])
.addTo(map);
function onDragEnd() {
var lngLat = marker.getLngLat();
coordinates.style.display = 'block';
coordinates.innerHTML =
'Longitude: ' + lngLat.lng + '<br />Latitude: ' + lngLat.lat;
//im not sure which input needs to get which value, you can change if needed
document.getElementById('hvalue').value = lngLat.lng
document.getElementById('wvalue').value = lngLat.lat
}
marker.on('dragend', onDragEnd);
</script>
</body>
</html>
so I'm trying to make a Google maps app for Android with Phonegap where I could add markers that have like a message. And the message is just stored locally for now. So I included a picture how the app looks now. Here is the App
So osoite means address, Viesti means message and lisää merkintä means add a note.
So here is the HTMl code for the index:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link rel="stylesheet"
href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="https://code.jquery.com/jquery-2.1.4.js"
integrity="sha256-siFczlgw4jULnUICcdm9gjQPZkw/YPDqhQ9+nAOScE4="
crossorigin="anonymous"></script>
<script
src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<title>Kartta</title>
</head>
<body>
<div id="pageOne" data-role="page">
<div data-role="header">
<h1>Kartta</h1>
</div>
<div role="main" class="ui-content ui-body-a">
<div id="geolocation" style="width: 285px; height: 370px;">
</div>
<div role="main" class="ui-content ui-body-a">
<p id="pageOne">
</p>
</div> <!-- /content -->
</div>
<div data-role="footer">
<label for="textinput-hide" class="ui-hidden-accessible">Osoite</label>
<input type="text" class="Osoite" name="textinput-hide" id="textinput-hide" placeholder="Osoite"
<br>
<label for="textinput-hide" class="ui-hidden-accessible">Viesti</label>
<input type="text" class="Viesti" name="textinput-hide" id="textinput-hide" placeholder="Viesti">
<br>
<button class="ui-btn">Lisää merkintä</button>
</div> <!-- /footer -->
</div>
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=(My own key)">
</script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">
$(document).on("pageOne", "#marker", function () {
$.ajax({
url: "https://maps.googleapis.com/maps/api/geocode/json?address=1600+Ratapihantie,+Pasila,+FI&key=(My own key)",
datatype: "json",
timeout: 5000
})
.done(function(data) {
var marker= results[0].geometry.location.lat
var marker2= results[0].geometry.location.lng
})
});
app.initialize();
</script>
</body>
</html>
And here is the code for the Javascript:
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online',
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
// The scope of 'this' is event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
app.receivedEvent('deviceready');
// Get our current location
navigator.geolocation.getCurrentPosition(app.onSuccess, app.onerror);
},
// Current location was found
// Show the map
onSuccess: function(position) {
var longitude = position.coords.longitude;
var latitude = position.coords.latitude;
var latLong = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
center: latLong,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("geolocation"), mapOptions);
},
// Current location could not be determined
// Show error
onerror: function(error) {
alert('code: ' +error.code + '/n' + 'message: ' + error.message + '\n');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
}
};
I just need help with adding the marker with the message.
You can use Google Map API for adding markers in map.
For simple marker, use this code:
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
For more details, Check out:
https://developers.google.com/maps/documentation/javascript/examples/marker-simple
I am having a problem deleting user added markers upon a new marker being add. I originally tried to go about the right click method but I only want the user to be able to create one marker at a time. Can someone please help me?
function addMarker(location){
marker = new google.maps.Marker({
position: location,
map: GlobalMap,
draggable: true,
animation: google.maps.Animation.DROP,
clickable: true
});
var form = $("#form").clone().show();
var contentString = form[0];
infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function(){
infowindow.open(GlobalMap,this);
});
infowindow.open(GlobalMap,marker);
markerPosition = marker.getPosition();
populateInputs(markerPosition);
google.maps.event.addListener(marker, "dragend", function (mEvent){
populateInputs(mEvent.latLng);
});
google.maps.event.addListener(marker, 'rightclick', function(){
marker.setMap(null)
});
}
google.maps.event.addDomListener(window, 'load', window.onload);
function populateInputs(pos){
document.getElementById("latitude").value=pos.lat()
document.getElementById("longitude").value=pos.lng();
}
function clearOverlays(){
for(var i = 0; i <markers.length; i++){
markers[i].setMap(null);
}
}
var markers= [];
var center= null;
var GlobalMap = null;
var marker = null;
var infowindow;
var geocoder = new google.maps.Geocoder();
window.onload = function() {
// Creating a reference to the mapDiv, which is defined in the host html file
var mapDiv = document.getElementById('map');
// Creating a latLng for the center of the map, these coordinates set the center of the initial map to the center of Springfield.
var latlng = new google.maps.LatLng(37.1950, -93.2861);
// Creating an object literal containing the properties
// we want to pass to the map
var options = {
center: latlng,
zoom: 11, // This zoom level shows the OTO area.
mapTypeId: google.maps.MapTypeId.ROADMAP // We want to show the data on the road map, as opposed to the satellite view.
};
// Now Creating the map
GlobalMap = new google.maps.Map(mapDiv, options);
oto.setMap(GlobalMap);
$('#address').keypress(function(e){
if(e.which==13){
e.preventDefault();
window.geocode();
}
});
markers.push(marker);
google.maps.event.addListener(GlobalMap, "click", function (event)
{
addMarker(event.latLng);
});
google.maps.event.addListener(marker, 'dragend', function(marker){
var latLong = marker.latLng;
$latitude.value = latLong.lat();
$longitude.value = latLong.lng();
});
}
Here is the HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Public Comment</title>
<link type="text/css" href="css/style.css" rel="stylesheet" media="all" />
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=drawing&sensor=false"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
var otoTableId = '1gPq1ryMpY1S_ovp6pIl0LvqDJkGNUUGShPpDCxtj';
var GlobalMap = null;
//var Urbanlayer = new google.maps.KmlLayer('http://www.ozarkstransportation.org/GIS/OTOBoundary.kml',{preserveViewport:true, suppressInfoWindows:true});
</script>
<script type="text/javascript" src="js/map.js"></script>
</head>
<body>
<!-- Top Banner Bar !-->
<button onclick="toggle_visibility('checkboxes')" style="float: right;">Toggle legend</button>
<div id="banner"><img src="http://www.ozarkstransportation.org/GIS/OTOgraphicSmall.jpg" border="none" height= "66">
<input type="text" id="address" class="form-control" placeholder="e.g., 205 Park Central East, Springfield MO" size="35">
<span class="input-group-btn">
<button onClick="window.geocode()" class="btn btn-success" value=>
<span class="glyphicon glyphicon-map-marker"></span>Go
</button>
</span>
<em id = "banner_text" align="absmiddle">Left click to drop a marker.<br> Right click to delete most recent marker.<br>Cancel to reset with no markers.</em>
</div>
<!-- The Google Map Window !-->
<div id="map"></div>
<!-- The Layer Toggle Window !-->
<div id="checkboxes">
<h3>Left click to drop a marker.<br> Right click to delete marker.<br>Cancel to reset with no markers.</h3>
<br><input type="checkbox" id="NAME" checked="true" onClick="toggleOto()"/><i class="fa fa-minus"></i>OTO Boundary<br />
<table bgcolor="#FFFFFF"><tr><td>
<br>
<!-- <center><b><font color="#000000">Use "add a marker" tool to leave comment.<br> Drag marker to desired location.</font></b></center> !-->
<br>
<center><font size="-1">
OTO MPO |
<!-- #BeginDate format:Am1 -->August 20, 2015<!-- #EndDate --> |
<a target="_blank" href="http://www.ozarkstransportation.org/GIS/Disclaimer.pdf">Disclaimer</a>
</font><br>
<font size="-2">For best results view in Google Chrome</font><br></center>
</td></tr></table>
</div>
<!-- The Bottom Messaging !-->
<div id="container">
</div>
<div id="entryform">
<form role="form" id = "form">
<iframe id ="myFrame" src="https://docs.google.com/forms/d/1EjeuI7ddocJIUr8RALi_WZIuqgQlfgVG9WMqvKR0lSw/viewform?embedded=true" width="500" height="500" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>
<h4>Please copy and paste the Latitude and Longitude values into the above form.</h4>
<div class="form-group">
<label><b>Latitude</b></label>
<input id ="latitude" type="text" class="form-control" name="lat" `enter code here`placeholder="Latitude" required="yes">
</div><br>
<div class="form-group">
<label><b>Longitude</b></label>
<input id ="longitude" type="text" class="form-control" name="lng" placeholder="Longitude" required="yes">
</div><br>
<div class="form-group">
<!-- <button class="btn btn-primary" id="submit-button">Submit</button> !-->
<button class="btn btn-primary" id ="delete-button">Cancel</button>
</div>
</form>
</div>
</body>
</html>
Looks like your marker is already global. This should work:
function addMarker(location){
// check if the marker already exists and has a .setMap method
if (marker && marker.setMap) {
// remove existing marker from the map
marker.setMap(null);
}
// create the marker
marker = new google.maps.Marker({
position: location,
map: GlobalMap,
draggable: true,
animation: google.maps.Animation.DROP,
clickable: true
});
// ... rest of your code
I have a problem using responsive Google map on my page. I am using Google Map API v3 & bootstrap 3 CSS to make my site mobile first & responsive. I intend to get users address either by using Google places API by automatically filling up the address form or by getting coordinates from the map and GPS.
I am using radio button to enable user to select either of the two options. The address form is selected as default option. When Use Map option is selected, the form has to be hidden & the Google map should be visible in its place but that just won't happen. I used Mozilla's Inspect Element option to check if the map is loaded in the background & yes it did.
The problem:
The map just wont show up on the specified div which is div id="map-canvas" Except that everything works fine, I even managed to get static Google map as image to be displayed in the same div appending the image file to the div using .innerHTML() function.
The solution I need ia to be able to display the map inside the map-canvas div & the map should be responsive.
Here's my code (html + js + css) :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Address form</title>
<!-- Bootstrap Core CSS -->
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<!--Start of CSS for Google Places API-->
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
<style>
#locationField{
position: relative;
}
</style>
<!--End of assets for G Places API-->
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body onload="initialize()">
<div class="container">
<div>
<legend>Address</legend>
</div>
<form class="form-horizontal" action="" method="POST">
<fieldset>
<div class="well col-md-12">
<h4><strong>Where are you?</strong></h4><br /><br />
<legend></legend>
<div class="col-md-6">
<h4><strong>Your Information</strong></h4>
<legend></legend>
<div class="control-group">
<label class="control-label" for="location">Provide your location:</label>
<div class="controls">
<label class="radio-inline"><input id="loc_method" type="radio" name="loc_method" value="form" class="input-xlarge" checked required>Use Form </label>
<label class="radio-inline"><input id="loc_method" type="radio" name="loc_method" value="map" class="input-xlarge" onClick="getLocation()" required>Use Map </label>
<br />
</div>
</div>
<div class="address-form">
<div class="control-group">
<label class="control-label" for="address">Address</label>
<div class="controls">
<div id="locationField">
<input type="text" id="autocomplete" name="address" placeholder="Enter your address" class="form-control" required>
</div>
</div>
</div>
<br />
<div class="control-group">
<table class="table table-bordered table-hover">
<tr>
<td><label class="control-label">Locality</label></td>
<td><input class="form-control" id="street_number" name="tole" disabled="true"></input></td>
</tr>
<tr>
<td><label class="control-label">Street</label></td>
<td><input class="form-control" name="street" id="route" disabled="true"></input></td>
</tr>
<tr>
<td><label class="control-label">City</label></td>
<td><input class="form-control" id="locality" name="city_vdc" disabled="true"></input></td>
</tr>
<tr>
<td><label class="control-label">Region</label></td>
<td><input class="form-control" name="region" id="administrative_area_level_1" disabled="true"></input></td>
</tr>
<tr>
<td><label class="control-label">Zip code</label></td>
<td><input class="form-control" id="postal_code" name="zip" disabled=""></input></td>
</tr>
<tr>
<td><label class="control-label">Country</label></td>
<td><input class="form-control" name="country" id="country" disabled="true"></input></td>
</tr>
</table>
</div>
</div>
<div class="map-canvas control-group">
<div id="map-canvas">
<!--Map Should Be Here-->
</div>
</div>
</div>
<!-- Button -->
<div class="control-group col-md-12">
<br /><legend></legend>
<div class="controls">
<button type="submit" name="submit" class="btn btn-success pull-right">Submit</button>
<br /><br />
</div>
</div>
</div>
</fieldset>
</form>
</div>
<!--JS for Address Mode Selection-->
<script type="text/javascript">
$("input:radio[name=loc_method]:first-child").click(function(){
if($(this).val()=="form"){
$(".address-form").css("display","block");
$(".map-canvas").css("display","none")
}else{
$(".map-canvas").css("display","block");
$(".address-form").css("display","none");
}
})
</script>
<!--JS API For Google Places Address Form Autofill-->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<script type="text/javascript">
var y = document.getElementById("map-canvas");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError,{
enableHighAccuracy: true,
timeout:30000
});
} else {
y.innerHTML = "Geolocation is not supported by this browser, choose <b>Use Form</b> option to fill the address form.";
}
}
function showPosition(position) {
//These commented codes below are to display static GMap of the acquired coordinates as image in the div id="map-canvas" which I did successfully
/*var latlon = position.coords.latitude + "," + position.coords.longitude;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?center="
+latlon+"&zoom=14&size=320x240&sensor=true";
y.innerHTML = "<br />Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude +
"<br>Altitude: " + position.coords.altitude +
"<br>Position Accuracy: " + position.coords.accuracy +
"<br>AltitudeAccuracy: " + position.coords.altitudeAccuracy +
"<br><img src='"+img_url+"'>";*/
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("map-canvas"),myOptions);
//google.maps.event.addDomListener(window, 'load', initialize);
var point = new google.maps.LatLng(position.coords.atitude, position.coords.longitude);
var marker = new google.maps.Marker({
position:point,
map:map,
title:'Rescue Team Needed Here # <br />' + position.coords.latitude + 'deg. South & <br />' + position.coords.longitude + 'deg. East',
draggable:true,
});
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation. If you are concerned with your privacy choose <b>Use Form</b> option to fill the address form."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable. Choose <b>Use Form</b> option to fill the address form."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out. Choose <b>Use Form</b> option to fill the address form."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred. Choose <b>Use Form</b> option to fill the address form."
break;
}
}
</script>
<script>
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initialize() {
// Create the autocomplete object, restricting the search
// to geographical location types.
autocomplete = new google.maps.places.Autocomplete(
/** #type {HTMLInputElement} */(document.getElementById('autocomplete')),
{ types: ['geocode'],
componentRestrictions: {country: 'np'}});
// When the user selects an address from the dropdown,
// populate the address fields in the form.
google.maps.event.addListener(autocomplete, 'place_changed', function() {
fillInAddress();
});
}
// [START region_fillform]
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
// [END region_fillform]
// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
// [END region_geolocation]
</script>
Hope this you looking for.. which i understand from your question.
Define width:100%
#map-canvas {
margin: 20px 0;
padding: 0;
height: 300px;
float: left;
width: 100%;
}
HTML CODE
<div class="col-md-12">
<div id="map-canvas" style="position: relative; overflow: hidden; transform: translateZ(0px); background-color: rgb(229, 227, 223);"></div>
</div>
Adding class col-xs-12 to your map div will do the job.
Go ahead re-size the windows, the map will automatically resize, remaining in its div.
.yourdiv {
border: solid;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</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
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div class="yourdiv col-xs-12" id="map-canvas"></div>
</body>
</html>
I try to develop application with jquery mobile with phonegap. In first page register number is entered and then get the gps value using watchposition then update its location to sqlite database. in that i try to stop the watchposition using clearwatch() method. and i have the following error.
Uncaught TypeError: Object # has no method 'clearwatch'
my index.html
<!Doctype html>
<html>
<head>
<title>Geo position Aware Vehicle Locator</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0"/>
<script src="js/jquery-1.9.0.min.js"></script>
<link rel="stylesheet" href="css/jquery.mobile-1.3.0-rc.1.min.css"/>
<script src="js/jquery.mobile-1.3.0-rc.1.min.js"></script>
<script src="js/register.js"></script>
<script src="js/terminate.js"></script>
<script src="js/update.js"></script>
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
navigator.notification.alert("PhoneGap is ready!");
}
$(document).ready(function () {
$("#regis").click(register);
$("#start").click(update);
});
</script>
</head>
<body>
<div data-role="page" data-theme="b">
<div data-role="header" data-theme="b">
<p align="center">Vehicle Registration</a>
</div>
<div data-role="content" data-theme="b">
<label>Give Route Number</label>
<input type="text" id="rno"> <a href="#second" id="regis" data-transition="pop" data-role="button"
data-inline="true" data-icon="arrow-r" data-iconpos="right" data-mini="true"
data-theme="b">Register</a>
</div>
</div>
<div id="second" data-role="page" data-theme="b">
<div data-role="header" data-theme="b">
<p align="center">Vehicle Status</p>
</div>
<div data-role="content" data-theme="b">
<div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<h1>Current Location:</h1>
<h3> Latitude:</h3>
<p id="lat"></p>
<h3>Longitude:</h3>
<p id="long"></p>
<h3>Current Time:</h3>
<p id="utime"></p> <a id="start" data-role="button" data-theme="b">start</a>
<a id="terminate" data-role="button" data-icon="delete" data-iconpos="right" data-theme="b">Terminate</a>
</div>
</div>
</div>
</body>
</html>
and my terminate.js
document.addEventListener("deviceready", function () {
console.log("devicere");
if (navigator.network.connection.type == Connection.NONE) {
console.log("check con");
$("#terminate").text('No Internet Access')
.attr("data-icon", "delete")
.button('refresh');
}
});
var rno = localStorage.getItem('rno');//get value from local storage
console.log("rno=>", rno);
var watch_id = ''; // ID of the geolocation
var tracking_data = []; // Array containing GPS position objects
$("#start").on('click', function () {
watch_id = navigator.geolocation.watchPosition(
// Success
function (position) {
console.log(position);
var lat = position.coords.latitude;
console.log("lat", lat);
var lon = position.coords.longitude;
console.log("lon", lon);
var utime = position.timestamp;
console.log("position", utime);
$("#lat").html(lat);
$("#long").html(lon);
$('#utime').html(utime);
console.log('position' + lat + lon + utime);
$.ajax({
type: "POST",
url: "/update",
data: 'vid=' + rno + '&lat=' + lat + '&lon=' + lon + '&utime=' + utime,
cache: false
});
},
// Error
function (error) {
console.log(error);
},
// Settings
{ frequency: 3000, enableHighAccuracy: true });
});
//stop tracking gps value
$("#terminate").on('click', function () {
navigator.geolocation.clearwatch(watch_id);
var url = "/terminate";
$(location).attr('href', url);
});
it should be navigator.geolocation.clearWatch(watch_id); with a capital "W" in Watch.