I have a problem with my google map, its not displaying any markers at all. The data for the markers comes from wordpress post and custom fields.
I did a console log for var locations and the data is passed to this point. Also did a console log for var j and I'm getting there undefined.
What could be the problem that the markers are not displayed?
<?php
$args = array('post_type'=> 'investments'); $the_query = new WP_Query( $args );
if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post();
$investmentsData[$row]['meta'] = get_post_meta( $post->ID, 'investments_location_details', true );
$investmentsData[$row]['investment'] = [
'id' => get_the_id(),
'title' => get_the_title(),
];
foreach ($investmentsData as $key => $value) {
$investment = $value['tabs'];
$meta = $value['meta'];
}
wp_localize_script('jquery-core', 'investmentsData', $investmentsData);
?>
<div id="map"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: new google.maps.LatLng(54.233985, 16.8903183),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var locations = <?php echo json_encode($investmentsData) ?>;
var j = locations.length;
function initMap() {
for (i = 0; i < j; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(investmentsData[i].lat, investmentsData[i].lng),
map: map,
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(investmentsData[i].title);
infowindow.open(map, marker);
}
})(marker, i));
}
};
</script>
<?php
endwhile;
endif;
wp_reset_postdata();
wp_reset_query();
?>
UPDATE
The consol log for var locations is giving an object with
investment: {id: 192, title: "Post title"}
meta: {lat: "54.3765137", lng: "18.5707837"}
When I'm doing a console log of investmentsData[i].lat I get this Uncaught ReferenceError: investmentsData is not defined and for locations[i].lat I get this Uncaught TypeError: Cannot read property 'lat' of undefined
I'm inducing the API like this <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC5rsZHHAmzP_pOuHGKEUtarn2QideIyUM"></script>
Update from comment on answer
The locations variable is an object:
var locations = {"":{"meta":{"lat":"54.2427318","lng":"16.8870907"},"investment":{"id":386,"title":"Termoizolacja obiekt\u00f3w u\u017cyteczno\u015bci publicznej na terenie..."}}};
Issues with your code:
lat and lng are properties of the locations[i].meta object
title is a property of the locations[i].investment object
you aren't calling initMap
your map's center and zoom are set such that you can't see the marker.
proof of concept fiddle
update
per the information on your live page, locations is an object, not an array:
var locations = {"":{"meta":{"lat":"54.2427318","lng":"16.8870907"},"investment":{"id":386,"title":"Termoizolacja obiekt\u00f3w u\u017cyteczno\u015bci publicznej na terenie Gminy K\u0119pice"}}};
process that by using:
for (var obj in locations) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[obj].meta.lat, locations[obj].meta.lng),
map: map,
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[obj].investment.title);
infowindow.open(map, marker);
}
})(marker, i));
}
updated fiddle
code snippet:
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
<script type="text/javascript">
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng(54.233985, 16.8903183),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var locations = {
"": {
"meta": {
"lat": "54.2427318",
"lng": "16.8870907"
},
"investment": {
"id": 386,
"title": "Termoizolacja obiekt\u00f3w u\u017cyteczno\u015bci publicznej na terenie Gminy K\u0119pice"
}
}
};
for (var obj in locations) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[obj].meta.lat, locations[obj].meta.lng),
map: map,
});
console.log("marker position:" + marker.getPosition().toUrlValue(6));
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[obj].investment.title);
infowindow.open(map, marker);
}
})(marker, i));
}
};
initMap();
</script>
Here is a working example. With appropriate function calls and demo data.
function initMap() {
var locations = [{
investment: {
id: 192,
title: "Post title 1"
},
meta: {
lat: "54.3765137",
lng: "18.5707837"
}
},
{
investment: {
id: 193,
title: "Post title 2"
},
meta: {
lat: "54",
lng: "18"
}
}
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: new google.maps.LatLng(54.233985, 16.8903183),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var j = locations.length;
for (i = 0; i < j; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].meta.lat, locations[i].meta.lng),
map: map,
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i].investment.title);
infowindow.open(map, marker);
}
})(marker, i));
}
}
initMap();
#map {
height: 200px;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js"></script>
Related
In my laravel project am trying to show locations of my clinics in google maps (Taking lattitude and longitude values from php database). Follwoing is my code in controller.
public function showClinicLocations($id)
{
$clinic = Clinic::find($id);
$locations = Location::where('clinicID', $id)->get();
return view('clinic.locations')->with(['locations' => $locations ,'clinic'=>$clinic]);
}
In view page am properly getting locations .When i consoled the locations.length am getting the result as 12 , its correct and also am getting complete locations name.
But when i tried to show it in marker only 11 locations are showing in google map marker. Following is the code in google map marker.
<script>
// var services =<?php echo json_encode($services);?>;
// console.log(services);
function initMap() {
var locations = <?php echo $locations ?>;
console.log(locations.length);
var j;
for (j = 0; j < locations.length; j++) {
var map = new google.maps.Map(document.getElementById('map'),
{zoom: 8,
center: {
lat: parseFloat(locations[j]['locationLat']),
lng:parseFloat(locations[j]['locationLong'])
}
}
);
setMarkers(map);
}
}
function setMarkers(map) {
var locations = <?php echo $locations ?>;
//var services = <?php echo $services ?>;
//console.log(services);
for (var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
map: map,
position: {lat: parseFloat(locations[i]['locationLat']), lng:parseFloat(locations[i]['locationLong'])},
map: map,
title: locations[i]['locationName']
});
var infowindow = new google.maps.InfoWindow()
var content = locations[i]['locationName'];
google.maps.event.addListener(marker,'click',
(function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker, content,infowindow));
}
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
</script>
What is the problem with the code of google maps to show markers
You wanna generate the map only once and maybe also fit the map to the bounds of all displayed markers:
var locations = JSON.parse("<?php echo $locations ?>");
function initMap() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: {
lat: parseFloat(locations[0]["locationLat"]),
lng: parseFloat(locations[0]["locationLong"])
}
});
setMarkers(map);
}
function setMarkers(_map) {
var boundsToFit = new google.maps.LatLngBounds();
for (var i = 0; i <= locations.length; i++) {
var marker = new google.maps.Marker({
map: _map,
position: {
lat: parseFloat(locations[i]["locationLat"]),
lng: parseFloat(locations[i]["locationLong"])
},
map: _map,
title: locations[i]["locationName"]
});
var infowindow = new google.maps.InfoWindow();
var content = locations[i]["locationName"];
google.maps.event.addListener(
marker,
"click",
(function (marker, content, infowindow) {
return function () {
infowindow.setContent(content);
infowindow.open(_map, marker);
};
})(marker, content, infowindow)
);
boundsToFit.extend(marker.getPosition());
}
_map.fitBounds(boundsToFit);
}
The markers in my program just wont remove with the deleteMarkers() function
CSS:
#map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
HTML:
<div style="height:500px; width:750px;">
<div id="map-canvas"></div>
</div>
<select class="form-control" name="dateSelect" id="dateSelect" onchange="dateSelect_Event();"></select>
Javascript:
var map; <--- global variables
var locations = [];
var lat_get = '';
var long_get = '';
var marker=[];
var infowindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {lat: 7.072617, lng: 125.599494},
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 13,
});
};
function deleteMarkers() {
for (var i = 0; i < marker.length; i++ ) {
marker[i].setMap(null);
}
marker.length = 0;
}
function dateSelect_Event() {
deleteMarkers();
infowindow = new google.maps.InfoWindow({});
var locationsRef = firebase.database().ref("location");
locationsRef.on('child_added', function(snapshot) {
var data = snapshot.val();
marker = new google.maps.Marker({
position: {
lat: parseFloat(data.latitude),
lng: parseFloat(data.longitude)
},
map: map
});
marker.addListener('click', (function(data) {
return function(e) {
infowindow.setContent(this.getPosition().toUrlValue(6));
infowindow.open(map, this);
}
}(data)));
marker.setMap(map);
});
}
Firebase:
-databaseName
--location
---latitude
---longitude
I just use firebase to get the lat and long on every change of the html select option and it work perfectly. The problem this time is it can't delete the markers. Should I do the deleteMarkers differently?
Thanks to #StackSlave's answer. I was able to successfully remove it by creating and pushing the google_marker to the global marker variable.
function dateSelect_Event() {
deleteMarkers();
infowindow = new google.maps.InfoWindow({});
var locationsRef = firebase.database().ref("location");
locationsRef.on('child_added', function(snapshot) {
var data = snapshot.val();
var google_marker = new google.maps.Marker({
position: {
lat: parseFloat(data.latitude),
lng: parseFloat(data.longitude)
},
map: map
});
google_marker.addListener('click', (function(data) {
return function(e) {
infowindow.setContent(this.getPosition().toUrlValue(6));
infowindow.open(map, this);
}
}(data)));
marker.push(google_marker);
});
marker.setMap(map);
}
I'm trying to put my markers on google maps and add an InfoWindow to each single marker. I'm getting Cannot read property 'name' of undefined on this line after I click on one of the markers:
markers[i].name.open(map, marker);
Here's the complete script:
function initMap() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 3,
// zoom in on current location if available (not done yet...)
center: new google.maps.LatLng(5,5)
});
var markers = [
// put all markers in a markers array
#foreach ($markers as $marker)
new google.maps.Marker({
position: { lat: {{$marker->x}}, lng: {{$marker->y}} },
// infowindow for each marker with its name
name: new google.maps.InfoWindow({
content: "{{$marker->name}}"
})
}),
#endforeach
];
for (var i = 0; i < markers.length; i++) {
// add eventlistener for the infowindow we added earlier
google.maps.event.addListener(markers[i], 'click', function() {
markers[i].name.open(map, marker);
});
// add marker to map
markers[i].setMap(map);
}
}
I'm using Laravel 5.1 with the Blade templating engine.
This works (this in the click listener refers to the google.maps.Marker that was clicked):
for (var i = 0; i < markers.length; i++) {
// add eventlistener for the infowindow we added earlier
google.maps.event.addListener(markers[i], 'click', function() {
this.name.open(map, this);
});
// add marker to map
markers[i].setMap(map);
}
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 3,
// zoom in on current location if available (not done yet...)
center: new google.maps.LatLng(5, 5)
});
var markers = [
// put all markers in a markers array
// #foreach ($markers as $marker)
// New York, NY, USA (40.7127837, -74.00594130000002)
new google.maps.Marker({
position: {
lat: 40.7127837,
lng: -74.0059413
},
// infowindow for each marker with its name
name: new google.maps.InfoWindow({
content: "New York, NY, USA"
})
}),
// Newark, NJ, USA (40.735657, -74.1723667)
new google.maps.Marker({
position: {
lat: 40.735657,
lng: -74.1723667
},
// infowindow for each marker with its name
name: new google.maps.InfoWindow({
content: "Newark, NJ, USA"
})
}),
// Baltimore, MD, USA (39.2903848, -76.61218930000001)
new google.maps.Marker({
position: {
lat: 39.2903848,
lng: -76.6121893
},
// infowindow for each marker with its name
name: new google.maps.InfoWindow({
content: "Baltimore, MD, USA"
})
}),
// #endforeach
];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
// add eventlistener for the infowindow we added earlier
google.maps.event.addListener(markers[i], 'click', function() {
this.name.open(map, this);
});
// add marker to map
markers[i].setMap(map);
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
try this ?
for (var i = 0; i < markers.length; i++) {
// add eventlistener for the infowindow we added earlier
(function(i) {
google.maps.event.addListener(markers[i], 'click', function() {
//console.log(markers[i])
markers[i].name.open(map, markers[i]);
});
// add marker to map
markers[i].setMap(map);
})(i);
}
i have a problem with placing multiple marker in google map.here is my code.it display only one marker during page reloading and when page is complettly load then map is not display.
javascript code:
<head>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<script>
function initialize(lat,lon)
{
var myCenter=new google.maps.LatLng(lat,lon);
var mapProp = {
center:myCenter,
zoom:9,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker=new google.maps.Marker({
position:myCenter,
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
php code:
<?php
require_once 'geocode.php';
$addarray=array(0=>'a, ahmedabad,india',1=>'b,ahmedabad,india');
foreach($addarray as $add)
{
// define the address and set sensor to false
$opt = array (
'address' => urlencode($add),
'sensor' => 'false'
);
// now simply call the function
$result = getLatLng($opt);
// if status was successful, then print the lat/lon ?
if ($result['status']) {
echo '<pre>';
?>
<script>
initialize(<?php echo $result['lat'];?>,<?php echo $result['lon'];?>);
</script>
<?php
echo '</pre>';
}
}
?>
here first i got lat and lon according to address then i called javascript function to place marker.but something is missing or create a problem.
thanks in advance.
Thanks #Tudor Ravoiu for your help. it is solved by changing few things.
i have created array in json format in php and pass it to javascript.
<?php
require_once 'geocode.php';
$addarray=array(0=>'a,ahmedabad,india',1=>'b,ahmedabad,india',2=>'c,ahmedabad,india');
$lat1=array();
foreach($addarray as $add)
{
// define the address and set sensor to false
$opt = array (
'address' => urlencode($add),
'sensor' => 'false'
);
// now simply call the function
$result = getLatLng($opt);
// if status was successful, then print the lat/lon ?
if ($result['status'])
{
array_push($lat1,array($result['address'],$result['lat'],$result['lon']));
}
}echo json_encode($lat1);
?>
javascript code:
<script type="text/javascript">
var locations = <?php echo json_encode($lat1);?>;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(23.0171240, 72.5330533),
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
You have to set the array as a global var. Also notice that markers_array is an object that contain all the markers latitudes and longitudes and also other data if you want to initialize an infowindow also.
var markers;
var map;
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
for(i=0;i<markers_array.length;i++){
addMarker(markers_array[i].lat,markers_array[i].long);
}
function addMarker(lat,lng) {
var myLatlng = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker({
map: map,
position: myLatlng,
name: zip
});
markers.push(marker);
}
LATER EDIT:
Here is an example of the marker array in json format:
[
{
"name":"Marker 1 Italy",
"lat":"46.027482",
"long":"11.114502"
},
{
"name":"Marker 2 France",
"lat":"48.019324",
"long":"3.555908"
},
{
"name":"Marker 3 Spain",
"lat":"40.329796",
"long":"-4.595948"
}
]
I am using Google Map to display multiple lat/long points.
But the Google map Javascript code has the code snippet to track the center of lat/long of the available lat/long.
<script type="text/javascript">
var locations = JSON.parse('<?php echo json_encode($data);?>'); //alert (locations);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][2], locations[i][3]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][1]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
In Above code the line
center: new google.maps.LatLng(),
needs a lat/long pair which could be the center point of multiple lat/long to be displayed.
How could that be done?
This works. See the documentation of Map.fitBounds and LatLngBounds for details:
<script type="text/javascript">
var locations = JSON.parse('<?php echo json_encode($data);?>');//alert (locations);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][2],locations[i][3]),
map: map
});
bounds.extend(marker.getPosition());
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][1]);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
</script>
code snippet:
var locations = JSON.parse(
JSON.stringify([
['AAA', 'BBB', 42, -72],
['BBB', 'CCC', 42.1, -72.2]
])); //alert (locations);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][2], locations[i][3]),
map: map
});
bounds.extend(marker.getPosition());
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][1]);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
You should get the bounds of your added markers with the function map.getBounds().
It returns an object on which you can get the center bound.getCenter().
See Find center of multiple locations in Google Maps