Displaying google maps pinpoints near a certain specified location - javascript

I have a table with some locations. For example:
ID LAT LNG
1 40.759139 -73.979723
I am trying to get the user country and city from his IP address (let's say I have it and it's Germany, Berlin for example).
And then go over all the locations in my DB and select the ones that are near, or within that city (within the city is better) and display them on a map this way: http://code.google.com/apis/maps/documentation/javascript/examples/event-closure.html
Now i've seen this question:
how do i find near by locations to a given location using google map api
Which is not really what i'm looking for, although it's close.
Anyone knows how I can accomplish what i'm trying to do?
Thanks,

Figured it out, this is how you do it:
Note: $default holds the city lat/lng that you would like to initially display. mapEvents() returns an array with all lat/lng/title of the event.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(<?= $default ?>);
var myOptions = {
zoom: 9,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php
$pinpoints = mapEvents();
foreach ($pinpoints as $pinpoint) {
$loc = $pinpoint['UA_LAT'] . "," . $pinpoint['UA_LNG'];
echo("
var myLatlng = new google.maps.LatLng(" . $loc . ");
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: '" . $pinpoint['EVENT_NAME'] . "'
});
");
$loc = "";
}
?>
}
</script>

Related

how to create google maps marker with custom field values?

I just placed a google map on my website following the instructions from google maps API: https://developers.google.com/maps/documentation/javascript/adding-a-google-map
Copying that example works perfectly but I would like to get the position of the marker depending on a custom field created in each post from WordPress
<div id="map"></div>
<?php $lati = get_field( "gmapslat" ); ?>
<?php $lat = get_field( "gmapslng" ); ?>
<script>
function initMap() {
var lat = '<?php echo $lat; ?>';
var lng = '<?php echo $lng; ?>';
var uluru = {lat: lat, lng: lng};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
<script async defer
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDPGx6I2w6hzEmQNR2IrRKlFC9oUT-COvs&callback=initMap">
</script>
</div>
When do that the map just shows grey.
It seems there's a problem with your PHP variables. This PHP Variable $lng is not declared. So you are setting an undeclared PHP variable in Javascript variable lng.
I also noticed these lines:
<?php $lati = get_field( "gmapslat" ); ?>
<?php $lat = get_field( "gmapslng" ); ?>
Is this variable $lat value a longitude? If so, use $lng instead. Using meaningful names for variables would be helpful. Variable names must define the exact explanation of its content, regardless of programming language. Checking this blog 15 Best Practices of Variable & Method Naming might help.
Important: Use parseFloat() on each javascript variable width coordinates to return a floating point number. Else, it won't work and you'll just see a grey map. To learn more about definition and usage of parseFloat(), you can check JavaScript parseFloat() Function.
Below is a sample code using "-25.363, 131.044" as a sample coordinates returned by your PHP get_field() function:
<div id="map"></div>
<?php
function get_field($args) {
switch ($args) {
case 'gmapslat':
return '-25.363';
break;
case 'gmapslng':
return '131.044';
break;
}
}
$lat = get_field('gmapslat');
$lng = get_field('gmapslng');
?>
<script>
function initMap() {
var lat = parseFloat("<?php echo $lat; ?>");
var lng = parseFloat("<?php echo $lng; ?>");
var myLatLng = {lat: lat , lng: lng};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
Hope it could help and happy coding!

how to indicate multiple custom marker on map using fetch lat and long data from mysql db

i have try to fetch lat and long value from mysql db and pass those value on google map for show location marker on map
but currently i have fetch only last rows data so indicate marker only one place
how to display all location on map??
<?php
include "config.php";
$result="select * from ds_duty_history";
$a=mysqli_query($conn,$result);
// $count_row = mysqli_num_rows($a);
while ($b = mysqli_fetch_array($a)) {
$long_d=$b['lng'];
$lat_d=$b['lat'];
$result = array(array('latitude'=>$lat_d,'longitude'=>$long_d));
}
?>
<!doctype html>
<html>
<head>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOURKEY&callback=initMap">
</script>
<script type="text/javascript">
var map;
function initialize() {
// Set static latitude, longitude value
var latlng = new google.maps.LatLng(<?php echo $lat_d; ?>, <?php echo $long_d; ?>);
// Set map options
var myOptions = {
zoom: 16,
center: latlng,
panControl: true,
zoomControl: true,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// Create map object with options
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php
// uncomment the 2 lines below to get real data from the db
// $result = mysql_query("SELECT * FROM parkings");
// while ($row = mysql_fetch_array($result))
foreach($result as $row){ // <- remove this line
echo "addMarker(new google.maps.LatLng(".$row['latitude'].", ".$row['longitude']."), map);";}
?>
}
function addMarker(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: true, // enables drag & drop
animation: google.maps.Animation.DROP
});
return marker;
}
</script>
</head>
<body onload="initialize()">
<div style="float:left; position:relative; width:550px; border:0px #000 solid;">
<div id="map_canvas" style="width:550px;height:400px;border:solid black 1px;"></div>
</div>
</body>
</html>
currently display only one marker i.e last fetch record lat and long assign on map
how to display all place on map using mysql lat,long value?
The main problem you have here is that you're not actually collecting different results in your $result variable but overwrite it with the most recent one. The also seems to be some abuse of the variable $result which might be contributing to your confusion. Let's say we declare a new array and call it $rows. Then we can collect all the rows with the following code (to substitute your first snippet):
<?php
include "config.php";
$sql = "SELECT * FROM ds_duty_history";
$result = mysqli_query($conn, $sql);
$rows = [];
while ($row = mysqli_fetch_array($result)) {
$lon_d = $row['lng'];
$lat_d = $row['lat'];
// Use short-cut append syntax here so we add row and don't overwrite $rows
$rows[] = ['latitude' => $lat_d, 'longitude' => $long_d];
}
?>
Now in your display code (the second snippet) you would be able to iterate over $rows pretty much like:
foreach ($rows as $row){
// Do work with each $row here
}
Just as an aside, try to get used to using variable names that are as meaningful as possible and use new variables as much as you can. Trying to use short, generic variable names like $a will always lead to confusion since you won't know what it represents unless you find where you declared it every time. Trying to re-use a variable (like you did with $result) can make your life much more difficult since now even if you find an assignment to the variable, it is assigned many different times and (the way you used it) represents completely different types each time. Doing this one thing makes it just a little easier to get the hang of programming since at the very least you'll be able to read and make sense of your own intent when reading your own code.
Please try this code for display multiple marker on map
<script type="text/javascript">
var LocationData = <?php echo json_encode($result); ?>;
function initialize()
{
var myOptions = {zoom:12,mapTypeId: google.maps.MapTypeId.ROAD};
var map =
new google.maps.Map(document.getElementById('map-canvas'), myOptions);
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (var i in LocationData)
{
var p = LocationData[i];
var latlng = new google.maps.LatLng(p[0], p[1]);
bounds.extend(latlng);
var icon = { url: '<?php echo base_url();?>assets/frontend/assets/images/location_pin1.png', // url
scaledSize: new google.maps.Size(40, 70), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0) // anchor
};
var marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: true, // enables drag & drop
animation: google.maps.Animation.DROP
icon: icon
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

Use advanced custom fields value in js for google maps marker

I want to use advanced custom fields to place a Google Map icon. I prefer using the repeater field, but first i'am trying to accomplish a regular field. Image field output is url. I don't understand what i'm doing wrong?
Here is a snippet from my code:
<script>
<?php $image = get_field('marker'); ?>
function initialize() {
//add map, the type of map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: new google.maps.LatLng(52.355692, 5.619524),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//add locations
var locations = [
['Hotspot1', 52.355889, 5.619535,'<?php echo $image ;?>'],
['Hotspot2', 52.354349, 5.618924,'$get_google_map']
];
//declare marker call it 'i'
var marker, i;
//declare infowindow
var infowindow = new google.maps.InfoWindow();
//add marker to each locations
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,
icon: locations[i][3]
});
//click function to marker, pops up infowindow
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=hidden&callback=initialize">
</script>
<?php endwhile; ?>
</div>
<?php endif; ?>
Thanks in advance,
Gino
Missing an echo for $get_google_map. Not sure what that represents either since it's not defined
var locations = [
['Hotspot1', 52.355889, 5.619535,'<?php echo $image ;?>'],
['Hotspot2', 52.354349, 5.618924,'$get_google_map']
];
Should be
var locations = [
['Hotspot1', 52.355889, 5.619535,'<?php echo $image ;?>'],
['Hotspot2', 52.354349, 5.618924,'<?php echo $get_google_map ;?>']
];
Inspect the output in browser source to see what the locations array actually looks like or log it to your console with console.log(locations)
Thanks for your quick reply. I changed the code into this:
<script>
<?php $image = get_field('marker'); ?>
function initialize() {
//add map, the type of map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15
, center: new google.maps.LatLng(52.355692, 5.619524)
, mapTypeId: google.maps.MapTypeId.ROADMAP
});
//add locations
var locations = [
['Hotspot1', 52.355889, 5.619535, '<?php echo $image ;?>']
, ['Hotspot2', 52.354349, 5.618924, '<?php echo $image ;?>']
];
Because $get_google_map was from previous testing. But unfortunately the
$image doesn't output anything.

Showing Google Maps with coordinates as variables

I am currently looking for a way to display a Google Maps map within my page. So far I can show the map, but I want the coordinates to be variables.
My PHP variables are $lat and $lng
This is my code so far
<script src='https://maps.googleapis.com/maps/api/js?v=3.exp'></script><div style='overflow:hidden;height:440px;width:700px;'><div id='gmap_canvas' style='height:440px;width:700px;'></div><style>#gmap_canvas img{max-width:none!important;background:none!important}</style></div><script type='text/javascript'>function init_map(){var myOptions = {zoom:15,center:new google.maps.LatLng(<VARIABLE>,<VARIABLE>),mapTypeId: google.maps.MapTypeId.ROADMAP};map = new google.maps.Map(document.getElementById('gmap_canvas'), myOptions);marker = new google.maps.Marker({map: map,position: new google.maps.LatLng(<VARIABLE>,<VARIABLE>)});infowindow = new google.maps.InfoWindow({content:'<strong>Title</strong><br>London, United Kingdom<br>'});google.maps.event.addListener(marker, 'click', function(){infowindow.open(map,marker);});infowindow.open(map,marker);}google.maps.event.addDomListener(window, 'load', init_map);</script>
Thanks in advance
Create JS Object
var displayOnMap = {"lat":<?php echo $lat; ?>, "lng":<?php echo $lng; ?>};
Then pass it like
new google.maps.LatLng( displayOnMap.lat, displayOnMap.lng);

want to load multiple google maps with loop

i am using a php while loop to create a div class multiple times
so every time i have different lat lng
also in every loop i initialize a new map on a different div to create the map
and here is my code
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
var title= "Title";
var lat = <?php echo $lat; ?>;
var lng = <?php echo $lng; ?>;
var myLatlng = new google.maps.LatLng(lat,lng);
var mapOptions = {
zoom: 14,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('beezMapBig<?php echo $tmp;?>'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
}
</script>
everytime the load works with the different lat,lng but i dont have the map 100% loaded
(i cant post image due to low reputation...imagine that the map is loading like 50% with the rest grey blank)
now the weird part is that when i press f12 at any browser to run the console to see some problems/failures the map is getting 100% loaded and resized.
Any ideas why this occurs and why the code is running correctly when run the browser console??
Thanks in advance!!
Had same issue and solved by doing this.
write ready() function. and then place the window resize functions in the initialize method itself (before initializing the map). It will help.
I can use PHP and JS. I have array with 3 elements.
Firstly Im generating div with unique id
<?php $i=0; foreach ($array as $single) : $i++; ?>
<div id="map_<?php echo $i; ?>" style="width: 100%; height: 300px;"></div>
<?php endforeach; ?>
Then im opening script tag like this
<script>
var maps = [];
<?php $i = 0; foreach($array as $single): $i++; ?>
maps.push({
mapContainer: 'map_'+<?php echo $i; ?>,
lat: <?php echo $single['mapa_google']['lat']; ?>,
lng: <?php echo $single['mapa_google']['lng']; ?>,
});
<?php endforeach; ?>
function initMap() {
for(var i = 0; i < maps.length; i++)
{
// The location of Uluru
var uluru = {lat: maps[i].lat, lng: maps[i].lng};
// The map, centered at Uluru
var map = new google.maps.Map(
document.getElementById(maps[i].mapContainer), {zoom: 16, center: uluru}
);
// The marker, positioned at Uluru
var marker = new google.maps.Marker({position: uluru, map: map});
}
}
</script>
On the bottom on my page im using async script
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOURKEY&callback=initMap">
</script>
Of course in my array I have data for 3 google maps.

Categories