Mapbox script to html - javascript

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>

Related

Adding Google Maps API to React to calculate route between two points

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.

Uncaught ReferenceError: google is not defined when placing pins

I keep getting the google is not defined. This only happens when I try to put the pins on the map. The map shows up fine with no errors until I add all the lines after the initMap() function. I have seen similar posts but none of the answers resolved my issue. Thanks for any advice in advance
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="maps.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/tabletop.js/1.5.1/tabletop.min.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPduELA=" crossorigin="anonymous"></script>
<script type="text/javascript" src="maps.js"></script>
<title>Dr Office Data</title>
</head>
<body>
<div class="pageContainer">
<div id="map"></div>
</div>
<div class="sortContainer">
<button type="button" name="button">Click to Show Summary Markers</button>
<div class="stateDropdown">
<label for="stateList">Select a State</label>
<select class="" name="states">
<option value="ALL">All</option>
<option value="AL">Alabama</option>
<option value="CO">Colorado</option>
<option value="MS">Mississippi</option>
</select>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&callback=initMap"
async defer></script>
</body>
</html>
```
var markerData = [["FIRST","LAST","ADDRESS","PHONE",39.6387797,-104.8007541],["FIRST","LAST","ADDRESS","PHONE",39.6125868,-105.1377128],["FIRST","LAST","ADDRESS","PHONE",30.6940368,-88.0945316]]
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: new google.maps.LatLng(37.09024, -95.712891)
});
}
var infowindow = new google.maps.InfoWindow;
var marker, i;
for (i = 0; i < markerData.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(markerData[i][4], markerData[i][5]),
map: map
});;
}
```
Like Geocodezip said, your maps-related code needs to be placed within the callback function to ensure the API has loaded before the code is executed. Try this working jsfiddle. Full code below:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<title>Dr Office Data</title>
</head>
<body>
<div class="pageContainer">
<div id="map" style="height:400px;width:400px;"></div>
</div>
<div class="sortContainer">
<button type="button" name="button">Click to Show Summary Markers</button>
<div class="stateDropdown">
<label for="stateList">Select a State</label>
<select class="" name="states">
<option value="ALL">All</option>
<option value="AL">Alabama</option>
<option value="CO">Colorado</option>
<option value="MS">Mississippi</option>
</select>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" async defer></script>
<script>
var markerData = [
["FIRST", "LAST", "ADDRESS", "PHONE", 39.6387797, -104.8007541],
["FIRST", "LAST", "ADDRESS", "PHONE", 39.6125868, -105.1377128],
["FIRST", "LAST", "ADDRESS", "PHONE", 30.6940368, -88.0945316]
];
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: new google.maps.LatLng(37.09024, -95.712891)
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < markerData.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(markerData[i][4], markerData[i][5]),
map: map
});
}
}
</script>
</body>
</html>
Hope this helps!

I need advice with making a Google map based app

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

Not able to get result of Angularjs being displaying as expression in html page

I am newbie in Angularjs and I am trying to work on a google maps application using Angularjs. I am able to generate the expected results apart from one thing. When I included {{loc.co1}} to be printed as a table column. It is not showing the result and giving a null. I searched a lot and found that my appraoch is correct. The results are available in the javascript but then when accessing from html, they dont show up. Could you please help me with this.
The input is when we drawing a rectangle on the map and click on submit, the coordinate values should go into the table.
Also, below is a link of the work I did. Sorry for not following the format properly.
http://plnkr.co/edit/kh5cUJabvG2rPJUEbgyt?p=info
===========code ===================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="ISO-8859-1">
<title>Scientist Entry Map</title>
<link rel="stylesheet" href="ScientistMapPage.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" integrity="sha384-3ceskX3iaEnIogmQchP8opvBy3Mi7Ce34nWjpBIwVTHfGYWQS9jwHDVRnpKKHJg7" crossorigin="anonymous"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDVgNI2snXEm8Cu5y-dxk0Y1ep9Iv3SOC4&libraries=drawing,geometry,places" async defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
<!-- <script type="text/javascript" src="lodash.min.js"></script> -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<!-- <script src="https://code.angularjs.org/1.4.8/angular-route.min.js"></script> -->
<!-- <script type="text/javascript" src="angular.min.js"></script> -->
<!-- <script type="text/javascript" src="angular-google-maps.min.js"></script> -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-google-maps/2.3.3/angular-google-maps.min.js"></script> -->
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="ng-map.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="MapController" class="form-control">
<table>
<tr><td><h1>Map for selecting places</h1></td></tr>
<tr><td>
<input id="placeSearch" class="form-control" type="text" placeholder="Search Box">
<div id="map"></div>
<button class="btn btn-primary" type="reset" id="btnResetRect" placeholder="ResetMap">Reset Map</button>
<button class="btn btn-primary" type="submit" id="btnSubmitRect">Submit Location</button>
<input type="hidden" id="txtCoords">
<input type="text" id="text" value="{{locationsData[0].co1}}"/>
</td>
<td>
<table class="table table-striped table-bordered">
<tr>
<th>Place
</th>
<th>Coordinates-1
</th>
<th>Coordinates-2
</th>
<th>Coordinates-3
</th>
<th>Coordinates-4
</th>
<th>Delete</th>
</tr>
<tr ng-repeat="loc in locationsData">
<td>to be added</td>
<td>{{loc.co1}}</td>
<td>{{loc.co2}}</td>
<td>{{loc.co3}}</td>
<td>{{loc.co4}}</td>
<td><button type="submit" class="btn btn-primary" id="deleteLocation">Delete</button></td>
</tr>
</table>
</td></tr>
</table>
</div>
</body>
</html>
// Code goes here
var myApp = angular.module('myApp',[]);
myApp.controller('MapController',function($scope) {
$scope.rectShape;
$scope.locationsData =[];
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(25, 80),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
$scope.drawingMg = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
//google.maps.drawing.OverlayType.MARKER,
//google.maps.drawing.OverlayType.CIRCLE,
google.maps.drawing.OverlayType.POLYGON,
//google.maps.drawing.OverlayType.POLYLINE,
google.maps.drawing.OverlayType.RECTANGLE
]
},
polygonOptions: {
fillColor: '#BCDCF9',
fillOpacity: 0.5,
strokeWeight: 2,
strokeColor: '#57ACF9',
clickable: false,
editable: true,
draggable : true,
zIndex: 1
},
rectangleOptions:
{
fillColor: 'red',
fillOpacity: 0.5,
strokeWeight: 2,
strokeColor: 'red',
clickable: true,
editable: true,
draggable:true,
zIndex: 1
}
});
var c1,c2,c3,c4;
google.maps.event.addListener($scope.drawingMg, 'rectanglecomplete', function(rectangle) {
//document.getElementById('info').innerHTML += "rectangle points:" + "<br>";
$scope.rectShape= rectangle;
c1 = rectangle.getBounds().getNorthEast().lat() +"," +rectangle.getBounds().getNorthEast().lng();
c2 = rectangle.getBounds().getNorthEast().lat()+"," +rectangle.getBounds().getSouthWest().lng();
c3 = rectangle.getBounds().getSouthWest().lat()+"," +rectangle.getBounds().getNorthEast().lng();
c4 = rectangle.getBounds().getSouthWest().lat()+"," +rectangle.getBounds().getSouthWest().lng();
document.getElementById("txtCoords").innerHTML = c1 +"\n"+c2+"\n"+c3+"\n"+c4;
// alert(document.getElementById("txtCoords").innerHTML.toString());
//document.getElementById("info").innerHTML += ne +"," +sw+ "<br>";
});
$scope.drawingMg.setMap($scope.map);
$scope.clearButton = document.getElementById("btnResetRect");
$scope.map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push($scope.clearButton);
$scope.submitButton = document.getElementById("btnSubmitRect");
$scope.submitButton.onclick = function(){
alert(c1 +""+c2);
//$scope.locationsData =[];
$scope.locationsData.push({
co1 : c1,
co2: c2,
co3: c3,
co4: c4
});
alert($scope.locationsData.length);
// $scope.locationsDatac1 = c1;
// $scope.locationsDatac2 = c2;
// $scope.locationsDatac3 = c3;
// $scope.locationsDatac4 = c4;
alert($scope.locationsData[0].co1);
};
console.log("outside do click");
$scope.clearButton.onclick = function(){
if($scope.drawingMg.getDrawingMode()){
$scope.shape.setMap(null);
//$scope.shape.setBounds(null);
//$scope.drawingMg.getDrawingMode().setMap(null);
}
};
$scope.placeSearch = document.getElementById("placeSearch");
$scope.searchBox = new google.maps.places.SearchBox($scope.placeSearch);
$scope.map.controls[google.maps.ControlPosition.TOP_LEFT].push($scope.placeSearch);
$scope.map.addListener('bounds_changed', function () {
$scope.searchBox.setBounds($scope.map.getBounds());
});
$scope.markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
$scope.searchBox.addListener('places_changed', function () {
$scope.places = $scope.searchBox.getPlaces();
if ($scope.places.length == 0) {
return;
}
// Clear out the old markers.
$scope.markers.forEach(function (marker) {
marker.setMap(null);
});
$scope.markers = [];
var center;
$scope.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.
$scope.markers.push(new google.maps.Marker({
map: $scope.map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds = place.geometry.viewport;
} else {
bounds = place.geometry.location;
}
});
$scope.map.fitBounds(bounds);
});
});
You need to use ng-model in input,
<input type="text" id="text" ng-model="location" />
I have made some necessary changes, no it works
DEMO

Delete marker when new marker is added?

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

Categories

Resources