I'm trying to get the Lng and Lat from the marker that I set on the google maps api.
I automatically want the coordinates to take place in my html form.
It looks like I'm not getting the getPosition() right, because every other variable I use (something like var x = 34) does work.
My code:
<form action="send_nieuwcontainer.php" method="post">
Marker_name: <input type="text" name="markername"><br>
Coördinaten: <br>
Lng: <input id="inputlng" type="text" placeholder="<?php $lng; ?>" readonly="readonly">
Lat: <input id="inputlat" type="text" placeholder="<?php $lat; ?>" readonly="readonly"><br>
</form>
</div>
<script>
function initMap() {
var groningen = {lat: 53.218883, lng: 6.566298};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: groningen
});
map.addListener('click', function(e) {
clearMarkers();
addMarker(e.latLng, map);
});
}
var markers = [];
var lng = marker.getPosition().lng();
var lat = marker.getPosition().lat();
document.getElementById('inputlng').value = lng;
document.getElementById('inputlat').value = lat;
// Adds a marker to the map.
function addMarker(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map
});
markers.push(marker);
if (marker = true) {
document.getElementById('replaceMe').style.display = 'none';
document.getElementById('replacement').style.visibility = 'visible';
} else {
alert ("Does not work");
}
}
Does someone see what I'm doing wrong or maybe something I'm forgetting?
Note: I've already tried looking on stackoverflow and googlemaps api guide. They keep telling me to use getPosition()
As #Turnip said, the marker var is declared with var inside addMarker, so it's only accessible inside addMarker.
Try declaring marker outside the function like var marker; and then, inside the function, instead of using var marker = ..., use marker = ....
Related
i have this button and onclick i want to pass lat lng to initialize function for google map:
<button class="btn btn-block btn-primary" onclick="initialize()" id='latlng' lat="{{$data['clients_address']['lat']}}" lng="{{$data['clients_address']['lng']}}">
Map Location
</button>
i tried passing with this event but its not working and if with jquery then how can i pass to javascript function
$('#latlng').click(function(e){
var lng = $(this).attr('lng');
alert(lng,lat);
});
<script>
function initialize() {
//console.log(this.getAttribute('lat'));
var latlng = new google.maps.LatLng(28.535516,77.391026);
var map = new google.maps.Map(document.getElementById('map'), {
center: latlng,
zoom: 13
});
var marker = new google.maps.Marker({
map: map,
position: latlng,
draggable: false,
anchorPoint: new google.maps.Point(0, -29)
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function() {
var iwContent = '<div id="iw_container">' +
'<div class="iw_title"><b>Location</b> : Noida</div></div>';
// including content to the infowindow
infowindow.setContent(iwContent);
// opening the infowindow in the current map and at the current marker location
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
In your example, you first used a .click to an ID selector. If you really only have one button that calls initialize() on the page you can pass PHP variables directly to Javascript:
<script>
let lat = <?php echo json_encode($data['clients_address']['lng']); ?>;
let lng = <?php echo json_encode($data['clients_address']['lng']); ?>;
function initialize() {
...
}
</script>
If you have multiple initialize() triggers, you can use #Mahmoud answer or pass the values as function parameters.
<button class="btn btn-block btn-primary" onclick="initialize({{$data['clients_address']['lat']}}, {{$data['clients_address']['lng']}})" id="latlng">
Map Location
</button>
function initialize(lat, long) {
...
}
Personally I tend to use this + element attributes when I need to reference a standard attribute (ex: value, class) or the value is referenced in more than one place (ex: not only in initialize function). Also, consider using jQuery data method if you intend to use attributes.
Att,
First you need to pass the clicked element to the initialize like so
<button class="btn btn-block btn-primary" onclick="initialize(this)" id='latlng' lat="{{$data['clients_address']['lat']}}" lng="{{$data['clients_address']['lng']}}">
Map Location
</button>
then in your initialize function you will get the lat and lng
function initialize(element) {
var lat = $(element).attr('lat');
var lng = $(element).attr('lng');
.....
}
Edit: I solved the problem. Leaving it up in case someone needs something similar in the future.
I am trying to use google map api to get coordinates and save the information in a database. If the user drags the marker then a form is updated with the information. User can also enter the information manually in the form if she wants and the map will be updated with a new marker. Then the user can click submit and the information will be saved in the database.
<form action="{{ route('YOUR_ROUTE') }}" method="post" enctype="multipart/form-data">
<div class="form-group">
<div style="padding-top: 10px;">
<div id="map-location"></div>
</div>
{{-- visibility, lat, lng, location --}}
<input class="form-control" type="text" name="location_name" id="location_name" placeholder="Location">
<input class="form-control" type="text" name="latitude" id="latitude" placeholder="Latitude" style="max-width: 50%;">
<input class="form-control" type="text" name="longitude" id="longitude" placeholder="Longitude" style="max-width: 50%;">
<button type="submit" class="btn btn-primary">Post</button>
<input type="hidden" value="{{ Session::token() }}" name="_token">
</div>
</form>
<script>
//initialise and add the map
function initMap(){
// location of midtown manhattan
var midtown = {lat: 40.7549, lng: -73.9840};
// the maps centered at midtown
var map = new google.maps.Map(document.getElementById('map-location'),{zoom:17, center:midtown});
// the marker
var marker = new google.maps.Marker({position: midtown, map: map, draggable: true});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
marker.setPosition(pos);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
// dragged event of the marker
google.maps.event.addListener(marker, 'dragend', function(){
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
var address;
$('#latitude').val(lat);
$('#longitude').val(lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({latLng: marker.getPosition()}, function(result,status){
if(status == google.maps.GeocoderStatus.OK){
address = result[0].formatted_address;
// console.log(address);
$('#location_name').val(address);
}
else{
console.log('Geocode was not successful for the following reason: ' + status);
}
});
});
// when the place is changed in the location box the map updates
searchBox = new google.maps.places.SearchBox(document.querySelector( '#location_name' ));
google.maps.event.addListener(searchBox, 'places_changed', function(){
var places = searchBox.getPlaces(),
bounds = new google.maps.LatLngBounds();
for(var i = 0; place = places[i]; i++){
bounds.extend(place.geometry.location);
marker.setPosition(place.geometry.location);
}
map.fitBounds(bounds);
map.setZoom(15);
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
$('#latitude').val(lat);
$('#longitude').val(lng);
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places&callback=initMap"></script>
I updated my first post with the code that is working for me.
I couldn't update the map with the information from the form because I didn't include the places library while loading the Maps JavaScript API.
I couldn't see the updated coordinates after dragging the map marker because I didn't enable the geocoding api and didn't create a billing account with google cloud. I also restricted my API key.
Hope this helps.
I am trying to create a google map. the latitude and the longitude are from the database so I had to put those in a textbox then get its value in the script. I tried doing so but it doesn't work will you help me with this one; here's my JavaScript:
function initMap() {
var lat = document.getElementById('lat');
var lang = document.getElementById('lang');
var uluru = {lat: lat, lng: lang };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
Here's the html:
<input type="text" style="display: none" id="lat" value="7.8383054" />
<input type="text" style="display: none" id="lang" value="123.2966657" />
<div id="map" ">
</div>
JSfiddle
the "numbers" in the text fields are access using the .value property:
the lat/lng in a google.maps.LatLngLiteral must be numbers. (without the parseFloat the API throws these errors:
InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number
InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number
var lat = parseFloat(document.getElementById('lat').value);
var lang = parseFloat(document.getElementById('lang').value);
You need to actually call the initMap method (your fiddle isn't doing this)
updated fiddle
code snippet:
html,
body,
#map {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
<input type="text" id="lat" value="7.8383054" />
<input type="text" id="lang" value="123.2966657" />
<div id="map" ">
</div>
<script>
function initMap() {
var lat = parseFloat(document.getElementById('lat').value);
var lang = parseFloat(document.getElementById('lang').value);
var uluru = {lat: lat, lng: lang };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
Try:
var lat = document.getElementById('lat').value;
var lang = document.getElementById('lang').value;
Not really sure where your problem lies aside from not actually using the value of the text inputs or calling the function that returns those values but perhaps something long these lines might help get you started. If you are needing the user to enter different lat/lng coordinates then you would also need an event handler assigned to listen for changes or a button to submit the new coordinates.
<?php
/*
*/
?>
<!doctype html>
<html>
<head>
<title>Google maps</title>
<script src='https://www.google.com/jsapi' charset='utf-8'></script>
<script src='https://maps.google.co.uk/maps/api/js?key=APIKEY' charset='utf-8'></script>
<script type='text/javascript' charset='utf-8'>
function initMap() {
var uluru = {
lat: document.getElementById('lat').value,
lng: document.getElementById('lang').value
};
var options={
zoom: 4,
center: uluru
};
var map = new google.maps.Map( document.getElementById('map'), options );
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
document.addEventListener( 'DOMContentLoaded', initMap, false );
</script>
<style type='text/css' charset='utf-8'></style>
</head>
<body>
<div id='map'></div>
<div>
<input type='text' id='lat' value='7.8383054' />
<input type='text' id='lang' value='123.2966657' />
</div>
</body>
</html>
call initMap() function in body tag. it will load the map, the most important thing do you have api key ? you also need ssl to use google maps. means your url must be https://yourdomain.com
body onload="initMap()"
I'm trying to make a website with asp.net mvc 4 & EF6 where I want to pass values from MSSQL table to javascript. So far everything is working fine except if I pass Latitude & Longitude values for google-map-api function, map doesn't show up in my view. I used Html.HiddenFor helper to pass the value from <span>. Here are my codes,
Controller
public ActionResult BranchDetails(int BrId)
{
Branch branchDetails = abdb.Branches.Find(BrId);
return View(branchDetails);
}
View
<script>
function initialize() {
var marker;
var LatTag = document.getElementById("Lat");
var Lat = LatTag.getElementsByTagName("span");
var LngTag = document.getElementById("Lng");
var Lng = LngTag.getElementsByTagName("span");
var mapProp = {
center: new google.maps.LatLng(LatTag, LngTag),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
marker = new google.maps.Marker({
position: new google.maps.LatLng(Lat, Lng),
animation: google.maps.Animation.BOUNCE
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
<div class="container well" style="min-width: 100%; padding-right: 5px;">
<div id="googleMap"></div>
<span id="Lat">#Html.HiddenFor(model => model.Latitude)</span>
<span id="Lng">#Html.HiddenFor(model => model.Longitude)</span>
<h4><b>#Html.DisplayFor(model => model.Title)</b></h4>
<p><strong>Address:</strong> #Html.DisplayFor(model => model.Address)</p>
<p><strong>Contact No. :</strong> #Html.DisplayFor(model => model.ContactNo)</p>
<p><strong>Contact Person(s):</strong> #Html.DisplayFor(model => model.ContactPerson)</p>
</div>
</body>
Point to be noted that my Longitude & Latitude fields in MSSQL are set in varchar mode. I'm not sure if its causing the problem but just felt needed to inform. How can I solve this problem? Need this help badly. Tnx.
Nevermind, found my own solution. This worked for me, instead of giving span id, I gave Html.HiddenFor helper the id. For some reason javascript was not picking the id of the span I guess. Here are my codes,
<script>
function initialize() {
var marker;
var Lat = parseFloat(document.getElementById("Lat").value);
var Lng = parseFloat(document.getElementById("Lng").value);
var mapProp = {
center: new google.maps.LatLng(Lat, Lng),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
marker = new google.maps.Marker({
position: new google.maps.LatLng(Lat, Lng),
animation: google.maps.Animation.BOUNCE
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
<div id="googleMap"></div>
#Html.HiddenFor(model => model.Latitude, new { id = "Lat" })
#Html.HiddenFor(model => model.Longitude, new { id = "Lng" })
</body>
I have some jquery (below) with creates multiple maps on window load. However there is some strange behaviour with the maps, but no errors.
The problem is when the maps load they all have the same location on the map, even when multiple different lng and lats are set.
Below is the the code that create the map and some sample html of one of the maps's boxes.
The strange thing is that the maps have the same locations but there are not errors. Has anyone experienced this before or know why it's happening.
Cheers.
Js: (assume this is called onloand and some blank global arrays are set.)
var maps_boxes = {
initialise: function() {
$('.a_map').each(function(index) {
var map_box = $(this);
var map_id = map_box.find('.the_map').attr('id');
var lat = map_box.find('.lat').val();
var lng = map_box.find('.lat').val();
lat_lngs[index] = new google.maps.LatLng(lat,lng);
options[index] = {
zoom: 4,
center: lat_lngs[index],
mapTypeId: google.maps.MapTypeId.ROADMAP
};
maps[index] = new google.maps.Map(document.getElementById(map_id), options[index]);
});
}
};
Sample html of one map:
<div class="a_map">
<form class="map_data" >
lng:<input class="lng" type="text" value="0" /><br />
lat:<input class="lat" type="text" value="10" />
</form>
<div id="map_xxxxx" class="the_map" ></div>
</div>
If you are using the same code you posted, you are getting same value for both the latitude and longitude:
var lat = map_box.find('.lat').val();
var lng = map_box.find('.lat').val();
I tried initializing 2 different maps on same page it is working fine.