I really am a JS noob - I have never really used itbefore and am struggling using the marker clusterer google provide. I have rad the documentation
here is the code
<script src="http://localhost/wheredidmytweetgo/js/markercluster.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(
document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.setCenter(
new GLatLng( 56.65622649350222, -19.86328125), 2);
var mc = new MarkerClusterer(map);
function createMarker(point, text, title) {
var marker =
new GMarker(point,{title:title});
GEvent.addListener(
marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
<?php
foreach ($cluster_location as $location) {
?>
var marker = createMarker(
new GLatLng(<?php echo $location ?>),
'Marker text <?php echo $location ?>',
'Example Title text <?php echo $location ?>');
map.addMarker(marker);
<?php }
?>
}
}
cluster location is just an array of lat and longs - My code is working fine when just using the add.overlay however there are too many to make the map readable hence the need for clustering. I do load the clustering JS which I have I have included.
I create the clusterer object and pass in map as defined.
var markers = [];
//create array
I know I can create a JS array and pass this in to
var mc = new MarkerClusterer(map, markers);
But I simply dont have the JS knowledge to create an array at this time (I intend to learn) and the Google documentation advises you can iterate and add one at a time using addMarker
Hi Tom - Thanksfor the info - I have tried doing what you advised and have came up with the below:
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://localhost/wheredidmytweetgo/js/markercluster.js">
</script>
<script type="text/javascript">
function initialize() {
var center = new google.maps.LatLng(37.4419, -122.1419);
var map = new google.maps.Map(document.getElementById('map'), {
'zoom': 13,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
});
var markers = [];
<?php foreach ($cluster_location as $location) { ?>{
var marker = new google.maps.Marker({'position': <?php echo $location;?>});
markers.push(marker);
}
<?
}
?>
var markerCluster = new MarkerClusterer(map, markers);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<h3>A simple example of MarkerClusterer (100 markers)</h3>
<p>
Compiled |
Standard version of the script.
</p>
<div id="map-container"><div id="map"></div></div>
</body>
</html>
But my map still loads empty. I'm using literally the most basic google provided code now and just loading my own markers in. I know my markers positioning should be okay because when I go to view my page source I can see
{
var marker = new google.maps.Marker({'position': 40.0994425,-74.9325683});
markers.push(marker);
});
for each marker. any more help would really be appreciated!
Please check the examples on google maps utilities library page (link).
But basically to add instance of an object (a marker) to an array you have to define the array first so you need to do the var markers = []; above the loop where you create the markers. And then as you create the markers you have to add them to the markers array by calling the push method of an array (while you are at it go to MDN and read about arrays! if you want to learn it's good time to start there - there is a tutorial about JS there as well (link).
So inside of the foreach loop afer you've defined a marker just add it to the array markers.push(marker); This will make the markers available for the MarkerCluster initialization.
In a longer term when you figure out javascript a bit better you'll probably want to replace this part with either passing data as JSON object to the DOM so methods can handle it or even better - have the data for markers be retrieved with ajax query. But one step at a time I guess :)
Maybe try the fun interactive tutorials at the www.codecademy.com? They are quite basic but seems like that's exactly what you need
EDIT:
var marker,
markers = [];
<?php foreach ($cluster_location as $location) { ?>
marker = new google.maps.Marker({'position': <?php echo $location;?>});
markers.push(marker);
<? } ?>
Related
I am using google geocode to convert an address into lat/lng coordinates and then searching my db for other 'articles'(actually store addresses) that are nearby. This is working and my 'locations' foreach loop works fine (If I look at the console I see an array). But when I go to add my markers nothing shows up. I'm not getting any errors with the code below but if I console.log(lat) it shows NaN.
The map shows up and it is centering correctly according to the var 'myLatlng', but no makers are showing. I saw on SO (HERE) that geocode creates a string so you need to parse string to float. But my attempt below is not working.
I'm using laravel 5.
If you want to see how I got my lat/lng coordinates see my answer to me own question HERE.
My template.blade.php page has this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=MYKEY&signed_in=true&libraries=places"></script>
The page I have the map has the script below these script tags.
Here's the relevant code for the page I have the map on. articles.index.blade.php
#section('footer')
<script>
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var myLatlng = new google.maps.LatLng(parseFloat({{ $article->lat }}),parseFloat({{ $article->lng }}));
var map_options = {
center: myLatlng,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options)
var locations = [
#foreach($articles as $article)
[{{$article->lat}}, {{$article->lng}}]
#endforeach
];
var lat = parseFloat(locations[0]);
var lon = parseFloat(locations[1]);
for (i = 0; i < locations.length; i++) {
var location = new google.maps.LatLng(lat, lon);
var marker = new google.maps.Marker({
position: location,
map: map,
});
}
}
google.maps.event.addDomListener(window, "load", initialize);
</script>
#stop
If I understood properly. You have this 'locations' array. Right? and those are the locations where the markers should appear. But if I'm not wrong, you could have a syntax error in this line:
var locations = [
#foreach($articles as $article)
[{{$article->lat}}, {{$article->lng}}], //YOU NEED A COMMA TO SEPARATE EACH ELEMENT
#endforeach
];
Might be the API is not understanding that weird array with no commas separating each child :P
I want you to try this different logic and see if it works in this part:
//var lat = parseFloat(locations[0]); REMOVE THIS
//var lon = parseFloat(locations[1]); AND THIS
for (i = 0; i < locations.length; i++) {
var location = new google.maps.LatLng(locations[i][0], locations[i][1]);
var marker = new google.maps.Marker({
position: location,
map: map,
});
}
Leave the type as a String, no need to convert to float.
I have this code
http://jsfiddle.net/DanielMontenegro/7pdU4/3/
Now, supose that I want to put that map in a site to allow people to report some particular event through the geocoding service. I would like to ask how could I manage to get the address/coordinates of that event in a table, and gatherall the users reports into a single database.
There is a lot of goood information about interfacing the Google Maps API v3 with PHP/MySQL in the "Articles" section of the documentation
This one looks like it answers your question; From Info Windows to a Database: Saving User-Added Form Data
See below code and try it.
I am using php static array you can connect your database and create array according your requirement. see the array below.
<?php $item = array('jaipur, rajasthan,india', 'udaipur, rajasthan,india'); ?>
Below My Code Take a look.
<html>
<head>
<script src="http://maps.google.com/maps?file=api&v=2&key=AIzaSyDwFjOazEAe1MI7nHV6vUwkWytOp8LH2Zk" type="text/javascript"></script>
</head>
<body onload="initialize();">
<?php $item = array('jaipur, rajasthan,india', 'udaipur, rajasthan,india'); ?>
<script>
var map = null;
var geocoder = null;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
var addresses = ["<?php echo implode ('","', $item); ?>"]
var geocoder = new GClientGeocoder();
//var addresses = ["A II Z, Ibn Battuta Mall, Sheikh Zayed Road, 5th Interchange, Jebel Ali Village, Dubai","A. Testoni,Dubai Festival City Mall, Ground Floor, Dubai", "Abdulla Hussain Khunji, The Dubai Mall,Downtown, Abu Dhabi"];
var curIndex = 0;
function showAddress() {
var _cur = addresses[curIndex];
geocoder.getLatLng(
_cur,
function(point) {
if (!point) {
//alert(_cur + " not found");
//map.setCenter(new GLatLng(0, 0), 6);
//map.setUIToDefault();
} else {
//console.log(_cur+":"+point);
//alert(_cur);
var cafeIcon = new GIcon(G_DEFAULT_ICON);
// Set up our GMarkerOptions object
markerOptions = { icon:cafeIcon };
map.setCenter(point, 6);
var marker = new GMarker(point, markerOptions);
map.addOverlay(marker);
var sales = new Array();
sales = _cur.split("|");
//Add click event on push pin to open info window on click of the icon
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml("<p class='para1bold' style=\"font-weight: bold;\">Address <br /><span class='para1' style='font-weight:normal;'>" + sales[1] + "</span></p>");
});
//Provides map,satellite,hybrid and terrain views in the map along with zoom control
map.setUIToDefault();
}
//do next after done
curIndex++;
if(curIndex<addresses.length)
showAddress();
}
);
}
showAddress();
}
}
</script>
<div id="map_canvas" style="width:100%; height:750px;"></div>
</body>
</html>
You'll need to set up an action listener of some kind (preferably a listener that will listen for a user click on the map). Then, simply geocode the resulting lat/lng and store what you receive in your table.
User clicks a point on map.
Click event grabs what lat/lng the user clicked on.
The Lat/lng is geocoded for a textual address using Ajax.
Both Lat/lng and textual address are stored side-by-side in your database table.
I have a kml file with polygon data that is too complex to load onto one googlemap as it contains thousands of latlng coordinates that just wont load all at once.
My question is, is it possible to load just one polygon when a map marker is clicked? I have a mysql database table that holds the latlngs for each marker and the table also has a column for polyCoords. I am looping through the data using php which displays all the markers correctly. Can i then add a listener to the markers which will load the data from the polyCoords column and just show the polygon for that clicked map marker?
<script type="text/javascript">
function initialize()
{
var centre = new google.maps.LatLng(34.233753,-83.828712);
var myOptions =
{
zoom: 4,
center: centre,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php while ($row = #mysql_fetch_assoc($result))
{?>
var myLatlng = new google.maps.LatLng(<?php echo $row['lat'] . ',' . $row['lng']?>);
var marker = new google.maps.Marker
(
{
position: myLatlng,
map: map
}
);
<?php }?>
}
</script>
Thanks
Yes. Investigate AJAX.
There are some articles in the Google docs which may help: https://developers.google.com/maps/documentation/javascript/articles
Have a look at Using PHP/MySQL with Google Maps and Creating a store locator with PHP & MySQL. The latter covers getting data out of a database and updating what's shown on the map (it's markers rather a polygon boundary, but the technique is very similar).
If you run into a specific coding difficulty, ask a question about that.
I'm trying to use the Google Maps V3 API to create markers on a google map. I have the coordinates of the markers in mySQL database, and is currently in a PHP array in my .php file. Now how do I use a foreach() loop (or another suitable method) to loop through the elements in my PHP array and create a new google map marker with each iteration of the loop?
PS: My PHP is decent, but not my javscript knowledge. The tutorial I'm following now on creating the markers is at http://www.svennerberg.com/2009/07/google-maps-api-3-markers/
Code
I'm using Codeigniter framework, so the controller+model file already retrieved the necessary data(name, lng, lat...) into an array $map. I can loop the array using the usual method:
foreach($map as $row) {
$lng = $row[lng] // this is not necessary, its just to show what is in the array
$lat = $row[lat]
// now how do I use this loop to create new marker code in javascript?
}
The JS code for creating a google map marker which has to be created once per foreach loop iteration is like:
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng($lng, $lat), // how do i pass the PHP variables into the JS code?
mapTypeId: google.maps.MapTypeId.ROADMAP
});
So my question is how do i pass the PHP variables in the PHP array to create the JS code above, once per each foreach() loop iteration?
First of all, you are on the right track, but you just need to understand the separate concepts of server-side and client-side languages and how they can interact. PHP doesn't "pass" variables to JavaScript, but what it does do is generate whatever HTML document you want.
That HTML document then can contain JavaScript, which will execute as the page is rendered by the browser. So, think of your PHP as making the JavaScript code:
Example of PHP outputting JavaScript code in HTML page:
<script type="text/javascript">
var testval = "<?php echo "Hello, " . (5 + 3) . "!" ?>"; // "Hello, 8!
</script>
Now, I looked up the tutorial, and actually the code in your question is not the right code — instead it is the code to create the map, and the lat/long parameters in your example are for the center, not a marker.
So, in your PHP page, you want to do the following:
Somewhere, you need to create the map: var map = new google.maps.Map... (as shown in the tutorial)
Next, get the $map array with array items containing the 'lng' and 'lat' keys. (Note: you should always wrap array key names with quotes)
Inside an opened script tag use <?php to create a PHP code block, and create your foreach loop. For each item, create the JavaScript code needed to create the marker.
Example of foreach loop:
<script type="text/javascript">
<?php
foreach($map as $row) {
$lng = $row['lng'];
$lat = $row['lat'];
?>
// Creating a marker and positioning it on the map
new google.maps.Marker({
position: new google.maps.LatLng(<?php echo $lat ?>, <?php echo $lng; ?>),
map: map
});
<?php
}
?>
</script>
Usually the approach here is to encode the PHP data as JSON and then echo it into a Javascript variable:
<script type="text/javascript">
var myData = <?php echo json_encode($map); ?>;
</script>
which will output a Javascript literal you can use in your client-side scripting.
You'll want to loop this:
var marker;
<?php foreach($map as $row){ ?>
marker = new google.maps.Marker({
position: new google.maps.LatLng(<?php echo $row['lat'].','.$row['long']; ?>),
map: map
});
<?php } ?>
Just after the other code you included (which is to setup the map initially).
example to loop in JavaScript is as follows-
<script type="text/javascript">
"<?php echo $arr=array('1'=>'1','2'=>'2','3'=>'3','4'=>'4','5'=>'5');
foreach($arr as $k => $v){ ?>"
var x='<?php echo $v; ?>';
alert(x);
"<?php } ?>"
</script>
Replace $arr with your array and apply google map code in the script.
As #nrabinowitz said you can add the code in a ajax request
If your javascript is in the same page being loaded, you can add it in the same page.
<?php $c = 0;// counter ?>
<?php foreach ($map as $row):?>
var marker<?php echo $c?> = new google.maps.Marker({
position: new google.maps.LatLng(<?php echo $row['lat'].','.$row['long']; ?>), map: map });
<?php $c++; ?>
<?php endforeach;?>
THis way you wont overwrite the variable
Hi I have posted two values for latitute and longitute to a php page using a form, then on the php page I am displaying a googlemap and want to use the two values i posted as the latitude and longitute to plot on the map. I think iv done everything right but it doesnt seem to pick up the values.any ideas? cheers!
<script type="text/javascript">
function initialize() {
var lat= "<?php echo $_POST['coordinates']; ?>";
var long= "<?php echo $_POST['coordinatestwo']; ?>";
var latlng = new google.maps.LatLng(lat,long);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Your current location!"
});
}
</script>
</head>
<body onLoad="initialize();">
long is a reserved word in JavaScript. Try lng (no 'o') as your variable name instead.
var lng= "<?php echo $_POST['coordinatestwo']; ?>";
If you view source in your browser, do you see the php values there? If not then there is something wrong with your form. We would need to see more code.
But chances are it's the long being a reserved word issue I mentioned above.
Don't use long as a variable name (it's a reserved word). Also, you don't need quotes around numeric values. Try this:
var lat = <?php echo floatval($_POST['coordinates']); ?>;
var lng = <?php echo floatval($_POST['coordinatestwo']); ?>;
EDIT: Tip - if you use a (good) editor with color highlighting and syntax checking for JavaScript, this is an error that would be highlighted (mine reports: "strict warning: long is a reserver identifier").
I have a working jsFiddle here:
http://jsfiddle.net/rcravens/RFHKd/
Mostly your code. I added the following:
A 'div' with an ID of map_canvas
A style to this div giving it width and height.
Included the script to load google maps.
Hope this helps.
Bob
#paul elliot: That doesn't look like all your code..? See this example to fill in the bits your code is missing: http://code.google.com/apis/maps/documentation/javascript/examples/map-simple.html