Google Map, display data at marker label in Laravel/JS - javascript

The problem is when I pass the data controller to blade/JS, first I am converting it to JSON(because no other way) and then pass it to da javascript. But my label is not work properly. The script code is right below.
var estates = <?php echo json_encode($estates);?>
function initMap()
{
var options =
{
zoom : 10,
center : {lat:34.652500, lng:135.506302}
};
var map = new google.maps.Map(document.getElementById('map'), options);
for (var i=0; i < estates.length; i++) {
#foreach ($estates as $est)
var marker = new google.maps.Marker({
map: map,
label: estates.price,
position: {
lat: {{$est->lat}},
lng: {{$est->lng}}
}
});
#endforeach
}
}
So if I try to pass price is like this {{$est->price}} then I get syntax token error. Because price is varchar with Japanese characters. So I need to convert it Json first and itetare it. But when I do that, there are no markers and label in the map. Just empty map, also there is no error in the console too? If I delete the JS for loop then markers are coming but no label...
Is anyone know what am I missing here?

Try to use new google.maps.LatLng() function:
var estates = <?php echo json_encode($estates);?>
//estates = <?php echo json_decode($estates);?>
function initMap()
{
var options =
{
zoom : 10,
center : {lat:34.652500, lng:135.506302}
}
var map = new google.maps.Map(document.getElementById('map'), options);
for (var i=0;i<estates.length;i++){
var latLng_ = new google.maps.LatLng(estates['lat'],estates['lng']);
var marker = new google.maps.Marker({
map: map,
position: latLng_,
icon: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRAy10Br9W1wWCSQNPc6f9CarvNEO4qqCg1BDbe7_mYZqHwXj3v',
label: estates['price']
});
var infoWindow = new google.maps.InfoWindow({
content: estates['price']
});
marker.addListener('click', function () {
infoWindow.open(map, marker)
});
}
}

Related

Displaying google map markers from multiple json files

I have a database which contains addresses. I wish to display these addresses on a google map. I succeeded in generating a json file like this
$json = "https://maps.googleapis.com/maps/api/geocode/json?address=" . $row["HUISNUMMER"] . "+" . $row["STRAATNAAM"] . "+" . $row["STAD"] . "&key=MYPRIVATEKEY";
I can get the lat and long through php like this (in the same loop where I show the database records):
$jsonzip = file_get_contents($json);
$jsondata = json_decode($jsonzip,true);
$jsonlat = $jsondata['results']['0']['geometry']['location']['lat'];
$jsonlong = $jsondata['results']['0']['geometry']['location']['lng'];
And now I'm stuck turning these into markers.
For now I have the default google code to show a marker
<script>
function initMap() {
var myLatLng = {lat: 50.6847204, lng: 4.1045525};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
</script>
How would I add all the locations on the map?
You will first need to get the PHP variable into the javascript, an example:
<?php echo json_encode($jsondata); ?>
Then a for loop whith the creaton of a marker inside it. Something like:
for(var i = 0; i < jsondata.length; i++){
var marker = new google.maps.Marker({
position: jsondata[i]['geometry']['location']['lat'],
map: map,
title: 'Hello World!'
});
}
try this
$locations = json_decode($jsonzip, true);
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position : new google.maps.LatLng(locations[i]['geometry']['location']['lat'], locations[i]['geometry']['location']['lng']),
map : map,
animation : google.maps.Animation.DROP,
icon : new google.maps.MarkerImage( '/PATH/marker.svg', null, null, null, new google.maps.Size(24, 24) ),
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent('<h3>TITLE</h3>');
infowindow.open(map, marker);
}
})(marker, i));
}
for more informations: https://www.revilodesign.de/blog/google-maps-api/google-maps-api-karte-mit-mehreren-marker-und-infowindow/

remove marker from google maps by the id using javascript

I have a map with several markers where the location comes from firebase up to that point, all right. The problem is when the possiblity of the marked update it to create a new marker rather than deletes the old one.
I have already researched here on the site but none answered the question.
Either delete all or only one at a time.
That is why I am opening this new question. Thank you all right away.
<?php
mysql_select_db($database_vpt2, $vpt2);
$query_onlines = "SELECT * FROM motoristas WHERE `online` = 1";
$onlines = mysql_query($query_onlines, $vpt2) or die(mysql_error());
$row_onlines = mysql_fetch_assoc($onlines);
$totalRows_onlines = mysql_num_rows($onlines);
?>
<script type="text/javascript">
var markers = [];
function initMap() {
var myLatLng = {lat: -5.079166, lng: -42.812019};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: myLatLng
});
<?php do { ?>
var adaRef = firebase.database().ref("local/<?php echo $row_onlines['id_motorista']; ?>");
adaRef.on("value", function(snapshot) {
var rodar = parseInt(snapshot.val() .giro);
var lat1 = snapshot.val() .latitude;
var lng1 = snapshot.val() .longitude;
var myLatLng = {lat: lat1, lng: lng1};
var image = '../icon/marker.png';
var marker = new google.maps.Marker({
id: <?php echo $row_onlines['id_motorista']; ?>,
position: myLatLng,
map: map,
title: 'OK',
icon: image,
});
markers.push(marker);
});
<?php } while ($row_onlines = mysql_fetch_assoc($onlines)); ?>
}
</script>
You can update the marker by keeping the reference of markers in an array. Then update it something like below.
var myNewLatlng = new google.maps.LatLng(-2.363882,131.044922);
marker.setPosition(myNewLatlng);
Reference: https://developers.google.com/maps/documentation/javascript/3.exp/reference#Marker

How to show google map marker after x seconds without refresh google map?

How to display google map after every x seconds without google map refresh?
1.Markers latLong are coming from database.
2.Allocate that markers on google map.
3.Markers's latLong changes after 30 second.
Problem is google map get refreshed. All I want google map should display without refresh with updated LatLong.
Here is my code.
<script>
function initMap() {
var infowindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 19.9518684, lng: 73.7354084}
});
var image = '<?php echo $getImagePath; ?>'
for (var o in markers) {
lat = markers[ o ].lat;
lng = markers[ o ].lng;
address = markers[ o ].address;
var my = new google.maps.LatLng(lat, lng);
//console.log(my);
var marker = new google.maps.Marker({
position: my,
map: map,
icon: image,
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent("'" + address + "'");
infowindow.open(map, marker);
});
}
}
</script>
I tried google.maps.event.addDomListener(window, "load", initMap); and window.onload = initMap; but didn't work.
Can any one help me out?
I hope this small rewrite of your code will help you on your way. As it stands, there's a lot of information not present in the question, so I can only guess
// note these are globals because they are set in initMap and used outside of it
var image = '<?php echo $getImagePath; ?>';
var map;
var infowindow;
var markers = [/* some initially loaded markers loaded as if by majick unicorn farts */];
function initMap() {
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 19.9518684, lng: 73.7354084}
});
doMarkers(true);
}
function doMarkers(firstLoad) {
markers.forEach(marker => {
var lat = marker.lat;
var lng = marker.lng;
marker.my = new google.maps.LatLng(lat, lng);
if (firstLoad) { // marker has no marker the first time because it's not on a map yet
marker.marker = new google.maps.Marker({
position: marker.my,
map: map,
icon: image,
});
google.maps.event.addListener(marker.marker, 'click', function () {
infowindow.setContent("'" + marker.address + "'");
infowindow.open(map, marker.marker);
});
} else { // move existing marker
marker.marker.setPosition(marker.my);
}
}
}
function magicallyFindAndUpdateMarkerDataUsingUnicornFarts(marker) {
// find corresponding marker in markers array
// update lat, lng and address
}
function doSomeAjaxToGetNewMarkerPositionsAndCallCallback(cb) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'someURI');
xhr.onload = function() {
var data = JSON.parse(xhr.responseText);
data.forEach(function(marker) {
magicallyFindAndUpdateMarkerDataUsingUnicornFarts(marker);
});
cb()
}
xhr.send();
}
setInterval(function () {
doSomeAjaxToGetNewMarkerPositionsAndCallCallback(function() {
doMarkers(false);
});
}, 30000);
Of course, I can't see how markers are loaded (into markers in your code), nor can I tell you what doSomeAjaxToGetNewMarkerPositionsAndCallCallback or magicallyFindAndUpdateMarkerDataUsingUnicornFarts should be, because you haven't shown any code regarding markers at all

How can I use JavaScript in Razor for google maps API

I am trying to use a 'foreach' loop to place a series of markers on the map using coordinates from a database. The retrieval of the data is not an issue so for now I'm not bothered about the map showing the correct locations. The issue is that when inside the 'foreach' loop, any code for the marker placement is immediately passed over. Any ideas?
Here is the current code:
<script>
function myMap() {
var lat = 52.4283381;
var lng = -1.601519;
var myLatLng = { lat: 52.428381, lng: -1.601519 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(lat, lng)
});
}
</script>
<script>
#foreach (var mapVars in ViewData.Model)
{
<text>
var marker = new google.maps.Marker
({
position: new google.maps.LatLng (52.428381 , -1.601519),
map: map,
title: "" + i,
});
</text>
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBfvqLwEOTU3oFoiJOmmloYJFYUA801lF8&callback=myMap"></script>
Try serialize your ViewData.Model to a javascript object and than loop from there.
Something like this:
<script>
function myMap() {
var lat = 52.4283381;
var lng = -1.601519;
var myLatLng = { lat: 52.428381, lng: -1.601519 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(lat, lng)
});
}
</script>
<script>
window.data = #(Html.Raw(js.Serialize(ViewData.Model)));
var markers = [];
for(i = 0; i < window.data.length; i++)
{
markers.push(new google.maps.Marker
({
position: new google.maps.LatLng (52.428381 , -1.601519),
map: map,
title: "" + i,
}));
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBfvqLwEOTU3oFoiJOmmloYJFYUA801lF8&callback=myMap"></script>

Adding multiple markers from external json to Google Map in Javascript

I receive json data from a server and need to add them to a google map. It works fine, however, I only see one marker and I assume every time I add a marker it changes it to new coordinates and doesnt add an extra marker. How can I define markers as an array?
$.getJSON(url, function(data) {
var entry = data.feed.entry;
$(entry).each(function(){
for (var prop in this["gsx$instruments"]) {
//alert(this["gsx$instruments"][prop]);
listContacts(this["gsx$instruments"][prop])
var myLatLng = {lat: Number(this["gsx$ycor"][prop]), lng: Number(this["gsx$xcor"][prop])};
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 13,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: this["gsx$instruments"][prop]
});
}
// Column names are name, age, etc.
//$('.results').prepend('<h2>'+this.gsx$instruments.$t+'</h2><p>'+this.gsx$type.$t+'</p>');
});
});
Add a new function addMarker and use that function to include markers also keep the map variable outside the ajax call as well. updated code below
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 13,
center: {lat: LAT, lng: LONG}
});
function addMarker(position, map, title){
var marker = new google.maps.Marker({
position: position,
map: map,
title: title
});
}
$.getJSON(url, function(data) {
var entry = data.feed.entry;
$(entry).each(function(){
for (var prop in this["gsx$instruments"]) {
//alert(this["gsx$instruments"][prop]);
listContacts(this["gsx$instruments"][prop])
var myLatLng = {lat: Number(this["gsx$ycor"][prop]), lng: Number(this["gsx$xcor"][prop])};
addMarker(myLatLng,map,this["gsx$instruments"][prop]);
}
// Column names are name, age, etc.
//$('.results').prepend('<h2>'+this.gsx$instruments.$t+'</h2><p>'+this.gsx$type.$t+'</p>');
});
});
Essentially, you first need to add the markers to an array of markers
Suppose you have JSON providing the markers and supposing each marker has a name and coordinates attributes
function formatMarkers (){
// Loop through all of the JSON entries provided in the response
for (var i = 0; i < markersArray.length; i++) {
var markers = markersArray[i];
// Create popup windows for each record
var contentString = '<p><b>Name</b>: ' + markers.name + '</p>';
// Converts each of the JSON records into Google Maps Location format
formattedMarkers.push({
latlon: new google.maps.LatLng( markers.coordinates[1], markers.coordinates[0] ),
message: new google.maps.InfoWindow({
content: contentString,
maxWidth: 320
}),
username: markers.name
});
}
return formattedMarkers;
}
Then you need to render each of them
formattedMarkers.forEach(function (n) {
var marker = new google.maps.Marker({
position: n.latlon,
map: map,
icon: icon
});
// For each marker created, add a listener that checks for clicks
google.maps.event.addListener(marker, 'click', function () {
// When clicked, open the selected marker's message
n.message.open(map, marker);
});
marker.setMap(map);
}
I hope I've been helpful.

Categories

Resources