I Have a google map on my site. Users can drag the marker and the map will input the lat and lon into a form for me. See code below. I want to be able to get the address from the lat and lon and put it into my form at "locationbox".
<script src="multi_step_form.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
<script type="text/javascript">
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(49.25302534866034,-102.04825518471148);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.HYBRID
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
draggable: true,
position: myLatlng,
map: map,
title: "Your location"
});
google.maps.event.addListener(marker, 'dragend', function (event) {
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
});
}
</script>
I have another bit of code to look up the address that I got from https://203luv.wordpress.com/2011/10/21/google-maps-javascript-v3-api-how-to-get-address-from-coordinates-latitude-longitude/ but I just can't figure out how to blend them together.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
var lat = "12.1234";
var long = "98.7654";
var latlng = new google.maps.LatLng(sLat, sLong);
geocoder.geocode({"latLng":latlng},function(data,status){
if(status == google.maps.GeocoderStatus.OK){
var add = data[1].formatted_address; //this is the full address
alert(add);
for(var i=0; i<data[1].address_components.length; i++){
if(results[1].address_components[i].types[0] == "administrative_area_level_1"){
alert(results[1].address_components[i].short_name);
}
}
}
})
My html form looks like this
<div id="map_canvas" style="width: 450px; height: 450px; background-color: Black;"></div>
<div id="latlong">
<p><input size="20" type="text" id="latbox" name="lat" placeholder="Drag the marker on the map or type in the latitude"></p>
<p><input size="20" type="text" id="lngbox" name="lon" placeholder="Drag the marker on the map or type in the longitude"></p>
</div>
<input class="text_field" id="locationbox" name="location" placeholder="Location" type="text" >
Any help would be appreciated
I would suggest calling the reverse geocoder in the dragend event listener function:
google.maps.event.addListener(marker, 'dragend', function (event) {
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
var latlng = this.getPosition();
geocoder.geocode({
"latLng": latlng
}, function (data, status) {
if (status == google.maps.GeocoderStatus.OK) {
var add = data[1].formatted_address; //this is the full address
// alert(add);
for (var i = 0; i < data[1].address_components.length; i++) {
if (data[1].address_components[i].types[0] == "administrative_area_level_1") {
document.getElementById('locationbox').value = data[1].address_components[i].short_name;
}
}
}
});
});
proof of concept fiddle
code snippet:
var map;
function initialize() {
var geocoder = new google.maps.Geocoder();
var myLatlng = new google.maps.LatLng(49.25302534866034, -102.04825518471148);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
draggable: true,
position: myLatlng,
map: map,
title: "Your location"
});
google.maps.event.addListener(marker, 'dragend', function(event) {
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
var latlng = this.getPosition();
geocoder.geocode({
"latLng": latlng
}, function(data, status) {
if (status == google.maps.GeocoderStatus.OK) {
var add = data[1].formatted_address; //this is the full address
// alert(add);
for (var i = 0; i < data[1].address_components.length; i++) {
if (data[1].address_components[i].types[0] == "administrative_area_level_1") {
document.getElementById('locationbox').value = data[1].address_components[i].short_name;
}
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" style="width: 450px; height: 450px; background-color: Black;"></div>
<div id="latlong">
<p>
<input size="20" type="text" id="latbox" name="lat" placeholder="Drag the marker on the map or type in the latitude">
</p>
<p>
<input size="20" type="text" id="lngbox" name="lon" placeholder="Drag the marker on the map or type in the longitude">
</p>
</div>
<input class="text_field" id="locationbox" name="location" placeholder="Location" type="text">
Related
I know many thread discuss this but my code still doesn't work.
I'm using google places searchBox API.
My code:
function initMap(){
var map = new google.maps.Map(document.getElementById('peta'), {
center: {lat: -34.397, lng: 150.644},
zoom: 16
});
var infoWindow = new google.maps.InfoWindow({map: map});
// 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('Your Location.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
var input = document.getElementById('alamat');
var searchBox = new google.maps.places.SearchBox(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
document.getElementById('x').innerHTML(places.geometry.location.lat());
});
}
link script:
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&libraries=places"></script>
html:
<div id="peta" style="width:500px;height:380px;"></div>
<input type="text" id="x" readonly="readonly" name="x">
i put document.getElementById on my textbox but it still doesn't show the latitude. Where i should put this code?
in other thread:
var location= places.geometry.location;
var lat = location.lat();
but it's not working. How do I solve the problem?
Is your element #x an input text box?
If so try:
document.getElementById('x').value = places.geometry.location.lat();
That will add the latitude to the value of the input text box.
Is this what you are trying to achieve?
I've solve the problem.
as #Dammeul said, i place the
document.getElementById('x').value = place.geometry.location.lat();
inside of places.forEach(function (place))
Hope this helpful.
It will convert the address into latitude and longitude and also show the address in the map with the marker..You have just add your map API key
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
function initMap() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(23.684994, 90.35633099999995);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == 'OK') {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function showResult(result) {
document.getElementById('latitude').value = result.geometry.location.lat();
document.getElementById('longitude').value = result.geometry.location.lng();
}
function getLatitudeLongitude(callback, address) {
address = address || 'Dhaka,Bangladesh';
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback(results[0]);
}
});
}
}
var button = document.getElementById('show');
button.addEventListener("click", function () {
var address = document.getElementById('address').value;
getLatitudeLongitude(showResult, address)
});
</script>
<!doctype html>
<html>
<head>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 400px;
width: 800px;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body onload="initMap()">
<div>
<div id="map" style="width: 320px; height: 480px;"></div>
<div>
<input id="address" type="textbox" value="">
<input type="button" id="show" value="Show" onclick="codeAddress()">
</div>
<div>
<p>Latitude:
<input type="text" id="latitude" readonly />
</p>
<p>Longitude:
<input type="text" id="longitude" readonly />
</p>
</div>
</body>
</html>
const { GoogleMap, LoadScript } = require("../../");
const ScriptLoaded = require("../../docs/ScriptLoaded").default;
const mapContainerStyle = {
height: "400px",
width: "800px"
};
const center = {
lat: 38.685,
lng: -115.234
};
const onLoad = ref => this.searchBox = ref;
const onPlacesChanged = () => {
x = this.searchBox.getPlaces()
console.log(x[0]["geometry"]["location"].lat())
}
<ScriptLoaded>
<GoogleMap
id="searchbox-example"
mapContainerStyle={mapContainerStyle}
zoom={2.5}
center={center}
>
<StandaloneSearchBox
onLoad={onLoad}
onPlacesChanged={
onPlacesChanged
}
>
<input
type="text"
placeholder="Customized your placeholder"
style={{
boxSizing: `border-box`,
border: `1px solid transparent`,
width: `240px`,
height: `32px`,
padding: `0 12px`,
borderRadius: `3px`,
boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
fontSize: `14px`,
outline: `none`,
textOverflow: `ellipses`,
position: "absolute",
left: "50%",
marginLeft: "-120px"
}}
/>
</StandaloneSearchBox>
</GoogleMap>
</ScriptLoaded>
Hi, i tried this, and it works, i get the lat and long, I am using react+searchboxAPI please feel free to follow up, here is the documentation, I realised that you cant do x["geometry"]["location"].lat(), instead you'll need to iterate through each of the places that have been returned, to test it, I did
console.log( x[0]["geometry"]["location"].lat() ) just to get the first result.You can use the js map function or iterate through the array of 20 by using a for loop.. cheers
https://react-google-maps-api-docs.netlify.app/#!/StandaloneSearchBox/1
I have created my code below with the mouseover affect at the end, but it does not work. Have I put it in the wrong place? I just can't seem to get it to work. Eventually I would like to get a certain type of info displayed on them but each step at a time, trying to get the basic to work first.
<!DOCTYPE html>
<html>
<head>
<!-- Google Maps and Places API -->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
//declare namespace
var up206b = {};
//declare map
var map;
function trace(message)
{
if (typeof console != 'undefined')
{
console.log(message);
}
}
up206b.initialize = function()
{
var latlng = new google.maps.LatLng(52.136436, -0.460739);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
var geocoder = new google.maps.Geocoder();
up206b.geocode = function()
{
var addresses = [ $('#address').val(), $('#address2').val()];
addresses.forEach(function(address){
if(address){
geocoder.geocode( { 'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
});
}
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
</script>
</head>
<body onload="up206b.initialize()">
<div style="top: 0; right: 0; width:380px; height: 500px; float:right;padding-left:10px; padding-right:10px;">
<h1 align="center">Map Search</h1>
<div style="border:1px solid #ccc; background:#e5e5e5; padding:10px;" >
<form >
<br>
Location 1 <input type="text" id="address">
<br>
<br>
Location 2
<input type="text" id="address2">
<br>
<br>
<input type="button" value="Submit" onClick="up206b.geocode()">
</form>
</div>
</div>
<div id="map_canvas" style="height: 500px; width: 500px; float:right"></div>
You need to:
define contentString
associate the marker with the infowindow content. One way of doing that is with anonymous function closure as in this related question Google Maps JS API v3 - Simple Multiple Marker Example, or with an explicit createMarker function as in my example below.
Note: This approach will only work for approximately 10 addresses, after which it will run into the Geocoder rate limits.
function createMarker(latlng, html, map) {
var infowindow = new google.maps.InfoWindow({
content: html
});
var marker = new google.maps.Marker({
map: map,
position: latlng
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
}
proof of concept fiddle
code snippet:
var markers = [];
function createMarker(latlng, html, map) {
var infowindow = new google.maps.InfoWindow({
content: html
});
var marker = new google.maps.Marker({
map: map,
position: latlng
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
markers.push(marker);
}
//declare namespace
var up206b = {};
//declare map
var map;
function trace(message) {
if (typeof console != 'undefined') {
console.log(message);
}
}
up206b.initialize = function() {
var latlng = new google.maps.LatLng(52.136436, -0.460739);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
up206b.geocode();
}
var geocoder = new google.maps.Geocoder();
up206b.geocode = function() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
var bounds = new google.maps.LatLngBounds();
var addresses = [$('#address').val(), $('#address2').val()];
addresses.forEach(function(address) {
if (address) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
createMarker(results[0].geometry.location, address, map);
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
});
}
google.maps.event.addDomListener(window, "load", up206b.initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="address" value="New York, NY" />
<input id="address2" value="Newark, NJ" />
<input type="button" value="Submit" onClick="up206b.geocode()">
<div id="map_canvas"></div>
I want to create dynamic Google map based on Autocomplete Input. I have written the code as:-
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDeAtURNzEX26_mLTUlFXYEWW11ZdlYECM&libraries=places&language=en"></script>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
var map_options = {
center: {
lat: 19.0825223,
lng: 72.7411155
},
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('sale_map_canvas'),map_options);
var marker = new google.maps.Marker({
position:{
lat: 19.0825223,
lng: 72.7411155
},
map:map,
draggable:true
});
var city_options = {
types: ['(cities)'],
componentRestrictions: {country: "in"}
}
var locality_options = {
componentRestrictions: {country:"in"}
}
var city = new google.maps.places.Autocomplete(document.getElementById('sale_city'),city_options);
var locality = new google.maps.places.Autocomplete(document.getElementById('sale_locality'),locality_options);
google.maps.event.addListener(city,'place_changed',function(){
var places = city.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i,place;
for (i = 0; place=places[i]; i++)
{
console.log(place.geometry,location);
bounds.extend(place.geometry.location);
marker.setPosition(place.geometry.location);
}
map.fitBounds(bounds);
map.setZoom(15);
});
google.maps.event.addListener(locality,'place_changed',function(){
var places = locality.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i,place;
for (i = 0; place=places[i]; i++)
{
console.log(place.geometry.location);
bounds.extend(place.geometry.location);
marker.setPosition(place.geometry.location);
}
map.fitBounds(bounds);
map.setZoom(15);
});
</script>
<body>
<input id="sale_city" name="sale_city" type="text" class="validate" autocomplete="on" placeholder="" required>
<label for="sale_city">City</label>
<input id="sale_locality" name="sale_locality" type="text" class="validate" autocomplete="on" placeholder="" required>
<label for="sale_locality">Locality</label>
<div id="sale_map_canvas"></div>
</body>
The Map isn't showing up. Please Solve it..I've written the code by referring the video on https://youtu.be/2n_r0NDekgc
There are few issues in the code.
Map div "sale_map_canvas" is missing.
Map should be loaded on page load.
I have changed the code and now map is loading
<style>
#sale_map_canvas {
height: 100%;
}
</style>
<script src="http://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
var map;
function initialize() {
var map_options = {
center: {
lat: 19.0825223,
lng: 72.7411155
},
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('sale_map_canvas'),map_options);
var marker = new google.maps.Marker({
position:{
lat: 19.0825223,
lng: 72.7411155
},
map:map,
draggable:true
});
var city_options = {
types: ['(cities)'],
componentRestrictions: {country: "in"}
}
var locality_options = {
componentRestrictions: {country:"in"}
}
var city = new google.maps.places.Autocomplete(document.getElementById('sale_city'),city_options);
var locality = new google.maps.places.Autocomplete(document.getElementById('sale_locality'),locality_options);
google.maps.event.addListener(city,'place_changed',function(){
var place = city.getPlace();
var bounds = new google.maps.LatLngBounds();
console.log(place.geometry,location);
bounds.extend(place.geometry.location);
marker.setPosition(place.geometry.location);
map.fitBounds(bounds);
map.setZoom(15);
});
google.maps.event.addListener(locality,'place_changed',function(){
var place = locality.getPlace();
var bounds = new google.maps.LatLngBounds();
console.log(place.geometry.location);
bounds.extend(place.geometry.location);
marker.setPosition(place.geometry.location);
map.fitBounds(bounds);
map.setZoom(15);
});
};
google.maps.event.addDomListener(window, "load", initialize);
</script>
<body>
<input id="sale_city" name="sale_city" type="text" class="validate" autocomplete="on" placeholder="" required>
<label for="sale_city">City</label>
<input id="sale_locality" name="sale_locality" type="text" class="validate" autocomplete="on" placeholder="" required>
<label for="sale_locality">Locality</label>
<div id="sale_map_canvas"></div>
</body>
I am doing programming in codeigniter + ajax + javascript and I have to fetch the longitude and latitude based on the user's entry in textbox.
I am already get the right response from the controller but view is not able to convert those longitude and latitude into maps even maps are not load on the page.
Here you can see my code:
$(document).ready(function() {
function submitMe(selector)
{
//alert(selector);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/locationcontroller/getLocation",
data: {location:selector },
success:function(longitude){
// alert(selector);
locate=longitude.split(" ");
latlong(locate[0],locate[1],selector);
}
});
}
$('#address').blur(function(){
var add=$('#address').val();
// alert(add);
submitMe(add);
});
});
function latlong(lat,long,selector)
{
alert(lat);
alert(long);
var selector=selector;
var myLatlng = new google.maps.LatLng(lat,long);
var map;
var marker;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function initialize(){
var mapOptions = {
zoom: 18,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("myMap"), mapOptions);
marker = new google.maps.Marker({
map: map,
position: myLatlng,
draggable: true
});
geocoder.geocode({'latLng': myLatlng }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#latitude,#longitude').show();
selector=results[0].formatted_address;
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
google.maps.event.addListener(marker, 'dragend', function() {
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
selector=results[0].formatted_address;
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
}
#myMap {
height: 350px;
width: 680px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<form method="POST">
<div id="myMap"></div>
<!--<input id="" type="text" style="width:600px;"/><br/>-->
<input type="text" id="address" name="address" />
<input type="text" id="latitude" placeholder="Latitude"/>
<input type="text" id="longitude" placeholder="Longitude"/>
<input type="submit" name="submit">
</form>
code of view
code of the controller
Change your javascript to
$(document).ready(function () {
function submitMe(selector) {
//alert(selector);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/locationcontroller/getLocation",
data: { location: selector },
//success: function (longitude) {
error: function (longitude) { // error because jsfiddle doesn't support ajax
//alert(selector);
longitude = "1.0001203013 12.0000001";
locate = longitude.split(" ");
latlong(locate[0], locate[1]);
}
});
}
$('#address').blur(function () {
var add = $('#address').val();
// alert(add);
submitMe(add);
});
});
function latlong(lat, long) {
alert(lat);
alert(long);
var myLatlng = new google.maps.LatLng(lat, long);
initialize(myLatlng);
}
// RELEVANT CHANGE: move initialize function outside of latlng, and receives the coordinates as parameter.
function initialize(myLatlng) {
var map;
var marker;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
var mapOptions = {
zoom: 18,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("myMap"), mapOptions);
marker = new google.maps.Marker({
map: map,
position: myLatlng,
draggable: true
});
geocoder.geocode({ 'latLng': myLatlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#latitude,#longitude').show();
selector = results[0].formatted_address;
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
google.maps.event.addListener(marker, 'dragend', function () {
geocoder.geocode({ 'latLng': marker.getPosition() }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
selector = results[0].formatted_address;
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', function () {
// RELEVANT CHANGE: initialize function receives an initial value.
var initialLatlng = new google.maps.LatLng(1.55555, 10.55555);
initialize(initialLatlng);
});
#myMap {
height: 350px;
width: 680px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<form method="POST">
<div id="myMap"></div>
<!--<input id="" type="text" style="width:600px;"/><br/>-->
<input type="text" id="address" name="address" />
<input type="text" id="latitude" placeholder="Latitude"/>
<input type="text" id="longitude" placeholder="Longitude"/>
<input type="submit" name="submit" />
</form>
Relevant changes
move initialize function outside of latlng, and now receives the
coordinates as parameter.
initialize function receives an initial value
JSFiddle demo
I have this code of google map with coordinates values
the questions is how we can merge the text field of Lat & Lon into one field only,
so we need one text field only display the coordinated (Lat,Lon)
can any one help
the code is below
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?
sensor=false"></script>
<br />
Copy this number and past it in GPS field
<br />
<br />
<input id="divLon" type="text" />
<input id="divLat" type="text" />
<br />
<br />
<div id="map_canvas" style="width: 600px; height: 600px;"></div>
<script type="text/javascript">
var marker;
function initialize() {
var lat;`enter code here`
var lon;
navigator.geolocation.getCurrentPosition(function (location) {
lat = location.coords.latitude;
lon = location.coords.longitude;
var city = new google.maps.LatLng(lat, lon);
var mapOptions = {
zoom: 15,
center: city,
mapTypeId:
google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById
("map_canvas"), mapOptions);
var image = "icon.png";
marker = new google.maps.Marker({
position: city,
map: map,
draggable: true,
icon: image
});
google.maps.event.addListener(marker, 'position_changed',
function (event) {
update();
});
update();
}, function (positionError) {
alert("getCurrentPosition failed: " + positionError.message);
}, { enableHighAccuracy: true });
};
google.maps.event.addDomListener(window, "load", initialize);
function update() {
var lonlan = marker.getPosition();
var divLon = document.getElementById ("divLon");
var divLat = document.getElementById ("divLat");
divLat.value = lonlan.lat ();
divLon.value = lonlan.lng ();
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDfpx62iYkjhpz0J-
vu4Zz96vtWE2TFzQs&signed_in=true&callback=initMap"></script>
</body>
</html>
Try this code:
function update() {
var lonlan = marker.getPosition();
var divLat = document.getElementById ("divLat");
divLat.value = lonlan.lat ()+", "+lonlan.lng ();
}
Simplest solution, use the .toUrlValue method of a google.maps.LatLng
function update() {
var lonlan = marker.getPosition();
var divLatLon = document.getElementById("divLatLon");
divLatLon.value = lonlan.toUrlValue(6);
}
code snippet:
var marker;
function initialize() {
var lat;
var lon;
navigator.geolocation.getCurrentPosition(function(location) {
lat = location.coords.latitude;
lon = location.coords.longitude;
var city = new google.maps.LatLng(lat, lon);
var mapOptions = {
zoom: 15,
center: city,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById
("map_canvas"), mapOptions);
var image = "icon.png";
marker = new google.maps.Marker({
position: city,
map: map,
draggable: true,
icon: image
});
google.maps.event.addListener(marker, 'position_changed',
function(event) {
update();
});
update();
}, function(positionError) {
alert("getCurrentPosition failed: " + positionError.message);
}, {
enableHighAccuracy: true
});
};
google.maps.event.addDomListener(window, "load", initialize);
function update() {
var lonlan = marker.getPosition();
var divLatLon = document.getElementById("divLatLon");
divLatLon.value = lonlan.toUrlValue(6);
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="divLatLon" />
<div id="map_canvas"></div>