I have a MySQL database where I stored some marker position (along with some other information) which I loaded into google map. I followed the example -
http://code.google.com/apis/maps/articles/phpsqlajax.html
and it worked fine for me.
Now what I want to do is, suppose a user will be able to choose an id of a specific marker and clicking on a button it will be loaded onto the map. Not sure how to load the specific marker on the map dynamically.
Any sort of help will be appreciated.
I have set up an example here. I am using the Google Geocoding API to receive co-ordinates of the address entered by the user and creating the marker using Google API V3 as shown below
Ajax Request to get the co-ordinates
$.getJSON("getjson.php?address="+address,
function(data){
lat=data.results[0].geometry.location.lat;
lng=data.results[0].geometry.location.lng;
point= new google.maps.LatLng(lat,lng);
map.setCenter(point);
zoom = 14;
marker = createMarker(point,"<h3>Marker"+(markersArray.length+1)+" "+point+"</h3>",zoom);
});
PHP Code to return the co-ordinates
<?php
$address = $_GET['address'];
$address=str_replace(" ","+",$address);
if ($address) {
$json = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$address.
'&sensor=true');
echo $json;
}
?>
Creating the Marker
function createMarker(latlng, html,zoom) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
marker.MyZoom = zoom;
return marker;
}
First of all i see in your link that you use v2.Try to use v3 at least now that you are at the beginning since the v2 is deprecated.
As of your question i can only tell you the procedure and then you can make it happen.
1. User interaction
User interacts with UI and selects i.e. a range of prices(0-100).
2. Ajax request
The client sends an ajax request to server to get json with jquery getJson() or any other way.
3. Server Respond
A php page responds to your ajax call and make a query in mysql getting a resultset of position-markers,converts it in json and send it back.
4. Parse respond
Parse the json back to the client and create markers.
Hi I found this one great help
http://www.svennerberg.com/2012/03/adding-multiple-markers-to-google-maps-from-json/
Create a json object as given the link and pass it to javascript .
function createMarker(json){
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
}
}
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'm trying to make a map with google maps api, that displays a lot of markers from a MySQL Database. I did nearly everything as it is written in the Google Maps API Tutorial (https://developers.google.com/maps/articles/phpsqlajax_v3?hl=de).
My Problem:
I don't want to load all markers at once, but only those that are between the bounds of my current view.
For that my "phpsqlajax_genxml.php" gets the 4 edges of my current view as GET-variables. That works fine, but I don't know how to handle the javascript-part.
My first try was to insert a handler, that updates the map when the bounds change:
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
var swPoint = bounds.getSouthWest();
var nePoint = bounds.getNorthEast();
var swLat = swPoint.lat();
var swLng = swPoint.lng();
var neLat = nePoint.lat();
var neLng = nePoint.lng();
var qs = '&swLat=' + swLat + '&swLng=' + swLng + '&neLat=' + neLat + '&neLng=' + neLng;
downloadUrl("./includes/phpsqlajax_genxml.php?sess=<?php print session_id();
?>"+qs,function(data){
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
But that would update the map every milisecond while I'm scrolling arround the map. How may I update that only every second?
The main Problem is how to insert only the new Caches to the map and delete those that are out of my view. I have no idea how to do that.
Up to now the "DownloadUrl"-function downloads every milisecond every cache in that area and also downloads those that ones I have already downloaded, so you may see there every marker a thousand times.
May someone help me, please? :)
There may be different approaches, e.g.
always request all markers for the given bounds and remove all previously added markers
request only the markers for the given bounds that you haven't got already. Therefore you must collect the markers(e.g. the ID's) that are already drawn within the view and pass this list as parameter to the PHP-script, so that this script may use the list to filter the markers in the Query(Note: you better send the data via POST, otherwise you will reach very fast the limit for the URL-length)
Related to the removing of the markers that are not within the view:
when you really must remove the markers that are out of the view I have no better idea than iterating over all markers and removing(set the map-property to null) the markers that are not within the bounds of the map(may be determined via LatLngBounds.contains())
The other issue with the listener: you better listen for the idle-event of the map
I am displaying the google map using javascript api v3. I am now able to display the title on mouse over of the pin.But I want to display the details in a div on mouse over of the pin.Can anyone suggest a method for doing so?
Assuming details holds the information to display, marker is the pin to click and map is your map:
var contentDetails = "<div>" + details + "</div>"
var infowindow = new google.maps.InfoWindow( {content: contentDetails});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.open(map,marker);
});
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 am trying to figure out how to pass the latitude and longitude to a google map when my page loads. I am using the following code in the header of my page which works to generate the maps based on the hard-coded latitude and longitude:
var map1;
var map2;
$(document).ready(function(){
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(43.7620537, -79.3516683),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map1 = new google.maps.Map(document.getElementById("map-canvas-1"),myOptions);
var myOptions2 = {
zoom: 14,
center: new google.maps.LatLng(43.6918950,-79.5310706),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map2 = new google.maps.Map(document.getElementById("map-canvas-2"),myOptions2);
}
$("#maptabs").tabs({initialIndex:0,collapsible:true,select: function(){}});
In the body of the page I use the following PHP script to retrieve the correct latitude and longitude that I would like to map:
<?php
$google_maps_key='ABQIAAAAO-NJVsUOX31LQYJY1LUG8BSOYIDhzYrztjureJjDlAP7PmMi1xQsm9hQ6Z-LRdLFkCtIPr0FQBZxeQ';
$adr = urlencode(DLookup("Property Address", "tblproperties", "`Roll#`=".$id["pntysc"]["pn"]).", ".DLookup("municipalityname", "tblmunicipalities", "municipalitiescounty=".$county));
$url = "http://maps.google.com/maps/geo?q=".$adr."&output=xml&key=$google_maps_key";
$xml = simplexml_load_file($url);
$status = $xml->Response->Status->code;
if ($status='200') { //address geocoded correct, show results
foreach ($xml->Response->Placemark as $node) { // loop through the responses
$address = $node->address;
$quality = $node->AddressDetails['Accuracy'];
$coordinates = $node->Point->coordinates;
echo ("Quality: $quality. $address. $coordinates<br/>");
}
} else { // address couldn't be geocoded show error message
echo ("The address $adr could not be geocoded<br/>");
}
?>
Here is my question: How can I populate the maps using the $coordinates variable that is generated in the body of the page, when I have code in the header of the page that needs that particular value? What is the best practice in terms of populating the maps using variable latitude and longitude instead of having those values simply hard-coded?
Thanks.
You need to consider defining your Coordinates to display prior to displaying your header. That is, define everything your going to use in your google maps prior to anything being displayed. Place all data into arrays; $coordinates, $groups, etc. You don't have to build out an XML file. You can just use a mix of PHP to build out the Javascript used in your maps views. You can visit a WordPress example at:
http://www.dogfriendlyorlando.com/
There's an IFRAME in the page that displays the header map based on the information provided thru WordPress Posts.
I can't seem to paste in the entire code here.
Email me at jjwdesign - thru gmail and I'll send you the PHP code so you can look at it.
There's another more complex CRM example (SugarCRM - Google Maps project) at:
http://www.sugarforge.org/projects/jjwgooglemaps/
Cheers, Jeff Walters