pass lat lng to javascript laravel - javascript

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');
.....
}

Related

Hide a marker in Google Maps API Javascript

I am loading a bunch of markers based on a dataset that I am reading from Mongodb in my ejs file. I just loop through the markers to add them to the map and then a "click" eventlistener to display some comment for each marker in the infowindow:
var infowindow = new google.maps.InfoWindow();
var marker, i;
<%for (i = 0; i < <%=comments.length%>; i++) {%>
var LatLng = {lat: <%=comments[i].lat, lng: <%=comments[i].lng%>};
var marker = new google.maps.Marker({
position: LatLng,
map:map,
title: 'Click to see comment details',
id:'<%=comments[i]._id%>'
});
marker.addListener('click', (function(marker, i) {
return function() {
var contentString = `
<div class="comment-item">
<div id="bodyContent">
<p class="lead mt-2"><%=comments[i].textComment%></p>
</div>
</div>
<div>
<form style="display: inline" method="POST" action="/admin/comments/<%=comments[i]._id%>" class="approve-comment-form">
<input type="submit" value="Approve Comment" class="btn btn-success"/>
</form>
</div>
`
infowindow.setContent(contentString);
infowindow.open(map, marker);
}
})(marker, i));
<%}%>
What I am trying to do is to submit the form (approve the comment) using ajax code below. This basically, updates a field for that comment in my Mongodb document.
$(document).on('submit','.approve-comment-form', function(event){
event.preventDefault();
var editCommentData = $(this).serialize();
var editCommentAction = $(this).attr('action');
var $originalCommentItem = $(this).parent('.comment-item');
$.ajax({
url: editCommentAction,
data: editCommentData,
type: 'PUT',
originalItem: $originalCommentItem,
success: function(data) {
console.log(data)
}
});
})
So, the form submission works well and if I refresh the page, that marker will not be displayed on the map (Because the "ajax put" method toggles a switch from on to off for that marker and on page reload it won't be displayed), but the problem is that I want the marker to hide also with the form submit (Without the page refresh) so that I know I have already approved the comment inside it.

setting marker coordinates as variable

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 = ....

Load a google map with coordinates that is obtained from ajax jquery

I am having a html page.Initially the data of markers and map and points are coming from controller and below is the corresponding view where in the div 'map' the map is displayed
<script>
function getcoordinates(){
//to get coordinates using ajax jquery(latitude,longitude)
}
</script>
<?php echo $map['js']; ?>
<input type="text" id="myPlaceTextBox"/>
<input type="text" id="text_id" placeholder="Search id"/>
<input type='button' name='search_id' value='Search' onClick='getcoordinates()'/>
<div id='map' style="width:100%; height:100%;"><?php echo $map['html']; ?></div>
the div 'map' is already being used to show the map when the page loads.There is also a search with onClick that calls the getcoordinates() function and get the coordinates.I need to reload the map with the new coordinates in the same div 'map'.
I have written the below function which is called from ajax success block but map doesnt seem to load in that div map.
function initialize(lat,lng) {
var mapOptions = {
center: new google.maps.LatLng(lat,lng), //assign Seprately
zoom: 8,
scrollwheel: false
};
document.getElementById('map').style.display="block";
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var customMarker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map,
icon: 'http://maps.google.com/mapfiles/ms/micons/red.png'
});
alert("loading completed");
}

Pass MSSQL table values to javascript

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>

Google Map does not show the map with given langLat

I have the following code to generate a Google Map based on the given latLang , but it does not show any map.
I get the latLang from DB and store it in a hidden input, the using document.getElementById() I get the value and assign it to the map. But it fails? Why?
(34.686298727073016, 50.92648297548294)
Here is the Javascript Code to Generate the map:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&language=fa"></script>
<div id='map-canvas' style="width: 500px; height: 500px; border-radius: 10px; -webkit-border-radius: 10px; -moz-border-radius: 10px;">
</div>
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(document.getElementById('mapPosition').value);
var mapOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'منطقه مورد نظر در نقشه'
});
var infowindow = new google.maps.InfoWindow({
content: "<B>نقطه مورد نظر خود را در نقشه کلیک کنید</B>"
});
/*
google.maps.event.addListener(map, 'click', function(event) {
console.log(event);
marker.setPosition(event.latLng);
document.getElementById('mapPosition').value = event.latLng;
map.setCenter(event.latLng);
});*/
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<input type="hidden" value="<?php echo $item[0]['latLang']; ?>" name="mapPosition" id="mapPosition" />
The api takes two arguments e.g.
new google.maps.LatLng(-34.397, 150.644)
and it looks like you are passing it one
new google.maps.LatLng(document.getElementById('mapPosition').value);
I would advise looking here for your problem.
Either parse the value
(34.686298727073016, 50.92648297548294)
into two parameters, or have two inputs- one for long and another for lat.
try to give individual lat long values:
myLatLong = new google.maps.LatLng(lat, long)

Categories