im making a solution that does the geocoding , i can get coords from adresse , and put a marker over this adresse , im trying to make this marker draggabele and everytime i change the marker position with the mouse , i must get the new cooords , can someone help me ?
edit : Solution with event.addlistner
this is my code (js + html )
<!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&signed_in=true"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(34.042145, -4.997128);
var mapOptions = {
zoom: 5,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
var lg;
var lat;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.setZoom(16);
var lat = results[0].geometry.location.lat();
document.getElementById('latitude').value = lat;
var lg = results[0].geometry.location.lng();
document.getElementById('longitude').value = lg;
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
draggable : true
});
}
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">
<input id="latitude" type="textbox" >
<input id="longitude" type="textbox" >
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map-canvas"></div>
</body>
</html>
Use Google Maps' getPosition function:
google.maps.event.addListener(marker,"dragend",function(){
document.getElementById("latitude").value=marker.getPosition().lat();
document.getElementById("longitude").value=marker.getPosition().lng();
});
Related
I am trying to add lat and longtitude to my javascript which can be maually enter by user but it is not showing the map and if i remove the javascript to add lat and long it works fine.
function initMap()
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: test,
map: map
});
var marker = new google.maps.Marker({
position: test,
map: map
});
}
#map {
width: 50%;
height: 400px;
background-color: grey;
}
<html>
<title>Google Maps on webPage</title>
<body>
<input type="number" id="txtlat" name="txtlat" placeholder="Latitude">
<input type="number" id="txtlng" name="txtlng" placeholder="Longitude">
<button onclick="fncheck()">Click</button>
<div id="map"></div>
<script async defer src ="https://maps.googleapis.com/maps/api/js?key=AIzaSyCdldYO5Ho4VxIFD9jjvT6meNDGROs4w4c&callback=initMap">
</script>
<script>
var latlng = new google.maps.LatLng(x, y)
</script>
</body>
</html>
I have got an embedded map on my website which contains a marker point to my office address. However, I need users to be presented with the directions from their current location to my office location automatically through geolocation in web browser. Is it possible?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Find a route using Geolocation and Google Maps API</title>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function calculateRoute(from, to) {
// Center initialized to Naples, Italy
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(40.84, 14.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Draw the map
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
var directionsService = new google.maps.DirectionsService();
var directionsRequest = {
origin: from,
destination: to,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC
};
directionsService.route(
directionsRequest,
function(response, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
new google.maps.DirectionsRenderer({
map: mapObject,
directions: response
});
}
else
$("#error").append("Unable to retrieve your route<br />");
}
);
}
$(document).ready(function() {
// If the browser supports the Geolocation API
if (typeof navigator.geolocation == "undefined") {
$("#error").text("Your browser doesn't support the Geolocation API");
return;
}
$("#from-link, #to-link").click(function(event) {
event.preventDefault();
var addressId = this.id.substring(0, this.id.indexOf("-"));
navigator.geolocation.getCurrentPosition(function(position) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
$("#" + addressId).val(results[0].formatted_address);
else
$("#error").append("Unable to retrieve your address<br />");
});
},
function(positionError){
$("#error").append("Error: " + positionError.message + "<br />");
},
{
enableHighAccuracy: true,
timeout: 10 * 1000 // 10 seconds
});
});
$("#calculate-route").submit(function(event) {
event.preventDefault();
calculateRoute($("#from").val(), "govandi"));
});
});
</script>
<style type="text/css">
#map {
width: 500px;
height: 400px;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Calculate your route</h1>
<form id="calculate-route" name="calculate-route" action="#" method="get">
<label for="from">From:</label>
<input type="text" id="from" name="from" required="required" placeholder="An address" size="30" />
<a id="from-link" href="#">Get my position</a>
<br />
<label for="to">To:</label>
<input type="text" id="to" name="to" placeholder="Another address" size="30" />
<a id="to-link" href="#">Get my position</a>
<br />
<input type="submit" />
<input type="reset" />
</form>
<div id="map"></div>
<p id="error"></p>
</body>
</html>
I've slightly amended the code from https://www.sitepoint.com/find-a-route-y using-the-geolocation-and-the-google-maps-api/ to have a journey planner from user location to set destinations, using a select html form.
In case it is useful for anyone.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Find a route using Geolocation and Google Maps API</title>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function calculateRoute(from, to) {
// Center initialized somewhere near London
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(53, -1),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Draw the map
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
var directionsService = new google.maps.DirectionsService();
var directionsRequest = {
origin: from,
destination: to,
travelMode: google.maps.DirectionsTravelMode.TRANSIT,
unitSystem: google.maps.UnitSystem.METRIC
};
directionsService.route(
directionsRequest,
function(response, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
new google.maps.DirectionsRenderer({
map: mapObject,
directions: response
});
}
else
$("#error").append("Unable to retrieve your route<br />");
}
);
}
$(document).ready(function() {
// If the browser supports the Geolocation API
if (typeof navigator.geolocation == "undefined") {
$("#error").text("Your browser doesn't support the Geolocation API");
return;
}
$("#from-link, #to-link").click(function(event) {
event.preventDefault();
var addressId = this.id.substring(0, this.id.indexOf("-"));
navigator.geolocation.getCurrentPosition(function(position) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
$("#" + addressId).val(results[0].formatted_address);
else
$("#error").append("Unable to retrieve your address<br />");
});
},
function(positionError){
$("#error").append("Error: " + positionError.message + "<br />");
},
{
enableHighAccuracy: true,
timeout: 10 * 1000 // 10 seconds
});
});
$("#calculate-route").submit(function(event) {
event.preventDefault();
calculateRoute($("#from").val(), $("#to").val());
});
});
</script>
<style type="text/css">
#map {
width: 500px;
height: 400px;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Calculate your route</h1>
<form id="calculate-route" name="calculate-route" action="#" method="get">
<label for="from">From:</label>
<input type="text" id="from" name="from" required="required" placeholder="An address" size="30" />
<a id="from-link" href="#">Get my position</a>
<br />
<label for="to">To:</label>
<select id="to">
<option value="51.5548885,-0.108438">Arsenal's Emirates Stadium</option>
<option value="51.481663,-0.1931505">Chelsea's Stamford Bridge</option>
</select>
<br />
<input type="submit" />
<input type="reset" />
</form>
<div id="map"></div>
<p id="error"></p>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Find a route using Geolocation and Google Maps API</title>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function calculateRoute(from, to) {
var myLatLng = {lat: 19.056, lng: 72.921};
// Center initialized to Mumbai, India
var myOptions = {
zoom: 10,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Draw the map
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
var directionsService = new google.maps.DirectionsService();
var directionsRequest = {
origin: from,
destination: to,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC
};
directionsService.route(
directionsRequest,
function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
new google.maps.DirectionsRenderer({
map: mapObject,
directions: response
});
$('.distance-in-km').text(response.routes[0].legs[0].distance.value / 1000 + "km");
alert( response.routes[0].legs[0].distance.value / 1000 + "km" ); // the distance in metres
} else
$("#error").append("Unable to retrieve your route<br />");
}
);
}
$(document).ready(function () {
// If the browser supports the Geolocation API
if (typeof navigator.geolocation == "undefined") {
$("#error").text("Your browser doesn't support the Geolocation API");
return;
}
navigator.geolocation.getCurrentPosition(function (position) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
calculateRoute(results[0].formatted_address, "govandi");
} else {
var marker = new google.maps.Marker({
position: myLatLng,
title: 'Hello World!'
});
marker.setMap(mapObject);
$("#error").append("Unable to retrieve your address<br />");
}
});
});
calculateRoute($("#from").val(), "govandi");
$("#calculate-route").submit(function (event) {
event.preventDefault();
calculateRoute($("#from").val(), "govandi");
});
$('.verify-location > a').click(function(){
$('.verify-location').hide();
$('#calculate-route').show();
});
});
</script>
<style type="text/css">
#map {
width: 500px;
height: 400px;
margin-top: 10px;
}
#calculate-route {
display: none;
}
.verify-location > a {
cursor: pointer;
color: #FCA2A2;
}
</style>
</head>
<body>
<div class="verify-location">Is the your location incorrect? <a>Click here to enter your location manually</a></div>
<form id="calculate-route" name="calculate-route" action="#" method="get">
<label for="from">From:</label>
<input type="text" id="from" name="from" placeholder="An address" size="30" />
<button type="submit">Submit</button>
</form>
<div id="map"></div>
<p id="error"></p>
<p class="distance-in-km"></p>
</body>
</html>
I am trying to put info windows in for a Google Maps page. I am using an API to call data and also using the markerclusterer.js plugin. I've seen how to do it with with a JSON object or if the markers are within the JavaScript document but I don't understand how to apply it to calling from another API.
What am I doing wrong? Can you please explain?
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>API Test</title>
<!--jQuery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"rel="stylesheet">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<!--CSS-->
<link href="style.css" rel="stylesheet" type="text/css">
<!--JavaScript-->
<script src="script.js" type="text/javascript">
</script>
<script src="markerclusterer.js" type="text/javascript">
</script>
</head>
<body>
<div class="container">
<br>
<div id="content">
<br>
<div id="googleMap"></div><br>
<footer id="footer">
<p>Footer</p>
</footer>
</div>
</div>
</body>
</html>
CSS:
#content {
box-shadow: 5px 5px 10px 5px black;
}
#googleMap {
height: 400px;
width: 100%;
border: 1px solid black;
}
JavaScript:
var map;
var MarkerClusterer;
var marker;
var mcOptions;
var markers = [];
$(document).ready(function() {
//Construct the query string
url ='https://opendata.howardcountymd.gov/resource/2rmt-d3f4.json?';
+ '$$app_token=3bEFB0E09z1w6zaJfAb6QqLsX';
function initialize() {
var mapProp = {
center: new google.maps.LatLng(39.287346, -76.964306),
zoom: 8,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById(
"googleMap"), mapProp);
var infowindow = new google.maps.InfoWindow({
content: "Hello World!"
});
google.maps.event.addListener(markers, 'click', function() {
console.log("hello world")
infowindow.open(map, Markers);
});
}
//google.maps.event.addDomListener(window, 'load', initialize);
initialize();
//Retrieve our data and plot it
$.getJSON(url, function(data, textstatus) {
$.each(data, function(i, entry) {
//Cluster Markers
for (var i = 0; i < 50; i++) {
var entryMarkers = entry[i];
var LatLng = new google.maps.LatLng(
parseFloat(entry.coordinates.latitude),
parseFloat(entry.coordinates.longitude)
);
}
var marker = new google.maps.Marker({
position: new google.maps.LatLng(
parseFloat(entry.coordinates
.latitude),
parseFloat(entry.coordinates
.longitude)),
map: map,
title: entry.file_name
});
markers.push(marker);
});
var markerCluster = new MarkerClusterer(map, markers);
});
//info windows
});
This is not valid:
google.maps.event.addListener(markers, 'click', function() {
console.log("hello world")
infowindow.open(map, Markers);
});
An event listener doesn't work on an array, needs to be added to each marker (that it applies to) individually.
You can use function closure to associate the infowindow to the marker (below example uses a createMarker function) and make the infowindow global. Note that you don't have to use function closure there are other ways to solve the issue. Below example puts the entry.file_name into the infowindow.
working fiddle
code snippet:
var map;
var MarkerClusterer;
var marker;
var mcOptions;
var markers = [];
var infowindow = new google.maps.InfoWindow({
content: "Hello World!"
});
$(document).ready(function() {
//Construct the query string
url = 'https://opendata.howardcountymd.gov/resource/2rmt-d3f4.json?' + '$$app_token=3bEFB0E09z1w6zaJfAb6QqLsX';
function initialize() {
var mapProp = {
center: new google.maps.LatLng(39.287346, -76.964306),
zoom: 8,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById(
"googleMap"), mapProp);
}
//google.maps.event.addDomListener(window, 'load', initialize);
initialize();
//Retrieve our data and plot it
$.getJSON(url, function(data, textstatus) {
$.each(data, function(i, entry) {
createMarker(entry);
});
var markerCluster = new MarkerClusterer(map, markers);
});
//info windows
});
function createMarker(entry) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(
parseFloat(entry.coordinates.latitude),
parseFloat(entry.coordinates.longitude)),
map: map,
title: entry.file_name
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
console.log("hello world");
infowindow.setContent(entry.file_name + "<br>" + marker.getPosition().toUrlValue(6));
infowindow.open(map, marker);
});
}
#input-area {
width: 100%;
border: 1px solid black;
}
#googleMap {
height: 400px;
width: 100%;
}
html,
body {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/googlemaps/v3-utility-library#07f15d84/markerclustererplus/src/markerclusterer.js"></script>
<!-- was https://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<div class="container">
<br>
<div id="content">
<br>
<div id="googleMap"></div>
<br>
<footer id="footer">
<p>Footer</p>
</footer>
</div>
</div>
I've looked at similar questions and can't quite figure this out, though I think I'm close.
The goal is to have a form which allows address input, and upon submit button click the address should be added as a marker on the already loaded map.
I've got garbled sample code all over the place, but here is what I've been working with(refactored from a Laravel 4 view):
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key="> // Placeholder API Key
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(29.428459, -98.492433), // Centered on downtown SA by default
zoom: 11
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<br>
<div id="user-input-form" style="width: 500px; height: 200px; margin-left: 20px;">
<input id="user-input" class="form-group form-control" name="user-input" type="text" value="112 E. Pecan St San Antonio TX 78205" placeholder="">
<button id="user-input-btn" class="btn btn-default" action="">Submit</button>
<p id="address-text"></p>
</div>
</div>
<div id="map-canvas" style="width: 500px; height: 400px;"></div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
function addMarker() { // Function to add markers on button click
var marker = new google.maps.Marker({
position: latlng, // set to location which corresponds with user input? Don't want to recenter map each time.
map: map,
draggable:false,
animation: google.maps.Animation.DROP,
title:"Marker #",
icon: "http://maps.google.com/mapfiles/ms/micons/blue.png"
});
}
$('#user-input-btn').click(function () {
var address = $('#user-input').val(); // Grab value of input field above
console.log(address);
$('#address-text').text('You entered: ' + address);
$('#address').text(address);
// Call addMarker function?
}); // end event from button click
</script>
</body>
</html>
Can anyone help me step through this? I'm trying to do something more complicated, but being able to:
Add markers via address submit through a form/button click.
Reset the map with a reset button to clear all the overlays.
Would be an awesome step forward.
Thank you
Okay thanks to kinakuta I was able to outline the following and implement it:
<script type="text/javascript">
$('#addr-btn').click(function () {
// Set variable address equal to user input
var address = $('#addr-value').val();
// Geocode address to get lat/lng
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function(result, status) {
if (status == google.maps.GeocoderStatus.OK) {
// console.log(result);
var latLngObj = result[0]["geometry"]["location"];
console.log(latLngObj);
}
// Create new marker based on lat/lng
var marker = new google.maps.Marker({
position: latLngObj,
map: map,
title:"Hello World!"
});
// Store marker in array to keep all markers on the page, and allow easy reset
});
});
</script>
Thanks!
I have made a Google Version 3 Geocoder , I want to be able to pick up the coordinates of the marker when it is dragged or clicked. Below is my code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script src="http://maps.google.com/maps/api/js?v=3.5&sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
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,
draggable: true,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
<style type="text/css">
#controls {
position: absolute;
bottom: 1em;
left: 100px;
width: 400px;
z-index: 20000;
padding: 0 0.5em 0.5em 0.5em;
}
html, body, #map_canvas {
margin: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body onload="initialize()">
<div id="controls">
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map_canvas"></div>
</body>
</html>
I have tried to use the following code to do this but it does not seem to work.
// Javascript//
google.maps.event.addListener(marker, 'dragend', function(evt){
document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});
google.maps.event.addListener(marker, 'dragstart', function(evt){
document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});
map.setCenter(marker.position);
marker.setMap(map);
//HTML//
<div id='map_canvas'></div>
<div id="current">Nothing yet...</div>
That code works just fine if you put it in the correct place:
http://www.geocodezip.com/BlakeLoizides_geocode.html
(inside the callback routine, the marker is local to it)