Getting current zoom level from a Google Map - php

I am using a google map in a PHP/MYSQL application. I get the code for the map form Goolge Docs and adapted a bit for the application.
New modifications are comming in the application and now the application need to know the 'current zoom level of the google map'. I check in internet but I didn't find a clear answer.
Is it possible to do it ? Is it mandatory to reload the page in every zoom change ?
This is the code and thanks.
<code>
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(latitude,longitude),
zoom: zoommapa,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
mapTypeId: 'roadmap'
});
// drap center
var image = 'images/icons/etapa/etapa.png';
var myLatLng = new google.maps.LatLng(latitude,longitude);
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("marquers_motor_3.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
//var name = 1;
var markers2 = [];
for (var i = 0; i < markers.length; i++) {
//var name = markers[i].getAttribute("name");
var image = markers[i].getAttribute("image");
var sombra = markers[i].getAttribute("sombra");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var orden = markers[i].getAttribute("order");
var name = markers[i].getAttribute("name"); // web_site email ciudad pais
var web_site = markers[i].getAttribute("web_site");
var email = markers[i].getAttribute("email");
var ciudad = markers[i].getAttribute("ciudad");
var pais = markers[i].getAttribute("pais");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
if (ciudad =="" || ciudad =='Desconocido') { ciudad = ""} else {ciudad =ciudad + " " }
if (!(web_site =="")) {web_site = "<a href='" + web_site + "' class='list' target='_blank'>" + web_site +"</a>"+"<br>"} else {web_site =""}
var html = "<div id='infoWindow'>" + orden + " - " + name + "<br>" + web_site + ciudad + " " + pais + "</div>";
//var name = name + 1;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: image,
shadow: sombra
});
var marker2 = new google.maps.Marker({
position: point
});
markers2.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
}
});
var mcOptions = {gridSize: 50, maxZoom: 15};
var MarkerClusterer = new MarkerClusterer(map, markers2,mcOptions);
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
//google.maps.event.addDomListener(window, 'load', initialize);

I assume the application needs to know the zoom level, but the zoom level is in user space (client side).
get the zoom level from the map with javascript (see https://developers.google.com/maps/documentation/javascript/reference?hl=nl#Map)
map.getZoom();
This has to be send back to the server using AJAX calls
Server can do with the zoom level what it wants
Keep in mind the fact that if multiple users can open the same map, zoom levels can be different so what would be the required behavior?

Yes, you can get the current zoom level of the map with the getZoom method of the google.maps.Map object.
If you need to trigger a method when the zoom changed then you can listen to the zoom_changed event of the google.maps.Map object. For further information about google.maps.Map object read: this
Consider the following example (to make it work: copy in notepad save the file as html and run it with Chrome):
<!DOCTYPE html>
<html>
<head>
<title>Getting Zoom Demo</title>
<style type="text/css">
html, body{ height: 100%; height: 100%; margin: 0; padding: 0; }
#map-container{ height: 100%; width: 100%; min-width:500px; min-height:300px; }
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
</head>
<body>
<div>
<label id="display-zoom-label">
</label>
</div>
<div id="map-container"></div>
<script>
// Global map variable to have access to map object everywhere in the code
var map,
firstBoundChangedListener,
markers = [];
// Add random markers
function addMarkers(count) {
// map is the google.maps.Map object
var bounds = map.getBounds();
var northEast = bounds.getNorthEast();
var southWest = bounds.getSouthWest();
var minLat = Math.min(northEast.lat(), southWest.lat());
var maxLat = Math.max(northEast.lat(), southWest.lat());
var minLng = Math.min(northEast.lng(), southWest.lng());
var maxLng = Math.max(northEast.lng(), southWest.lng());
var latDifference = maxLat - minLat;
var lngDifference = maxLng - minLng;
var latLngArray = new Array();
for (var i = 0; i < count; i++) {
var lat = minLat + Math.random() * latDifference;
var lng = minLng + Math.random() * lngDifference;
var latLng = new google.maps.LatLng(lat, lng);
latLngArray.push(latLng);
}
for (var i = 0; i < latLngArray.length; i++) {
var marker = new google.maps.Marker({
position: latLngArray[i],
title: "Marker: " + i
});
markers.push(marker);
marker.setMap(map);
}
}
function UpdateZoomLabel() {
var displayZoomLabel = document.getElementById("display-zoom-label"),
// get current zoom
zoomValue = map.getZoom();
displayZoomLabel.innerHTML = "The Current Map's Zoom is: " + zoomValue;
}
// Initialize the map object
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
};
map = new google.maps.Map(document.getElementById('map-container'), mapOptions);
firstBoundChangedListener = google.maps.event.addListener(map, "bounds_changed", function () {
if (firstBoundChangedListener) google.maps.event.removeListener(firstBoundChangedListener);
// call add markers: add 'n' markers randomly
addMarkers(6);
});
//Listen for the 'zoom_changed' event of the map
google.maps.event.addListener(map, "zoom_changed", function () {
//show zoom in label
UpdateZoomLabel();
});
UpdateZoomLabel();
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</body>
</html>

Related

Marker Cluster for data from MYSQL DB - Google Maps API

I have tried implementing a marker cluster into my code from the Google Developers Documentation but no joy so far. https://developers.google.com/maps/documentation/javascript/marker-clustering
Here is the snippet of code from my .JS file paying attention to the function showAllCustomers(allData) where I want to implement the Marker Clusterer:
var map;
var geocoder;
//Code to load the map with center point of Monterey MA
function initMap() {
var monterey = {lat: 42.181613, lng: -73.215013};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: monterey,
mapTypeId: google.maps.MapTypeId.HYBRID,
labels: true,
});
//collect customer data and geocoder object - declare geocoder as global
var cusdata = JSON.parse(document.getElementById('data').innerHTML);
geocoder = new google.maps.Geocoder();
codeAddress(cusdata);
var allData = JSON.parse(document.getElementById('allData').innerHTML);
showAllCustomers(allData)
var searchData = JSON.parse(document.getElementById('searchData').innerHTML);
showSearchedCustomer(searchData)
}
function showAllCustomers(allData) {
//declare info window variable outside of loop to allow to clear when selecting other markers
var infoWind = new google.maps.InfoWindow;
Array.prototype.forEach.call(allData, function(data){
var content = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = [data.lastName + ' ' + data.physicalAddress];
content.appendChild(strong);
//add image to infowindow - you are also able to add image path to mysql and then append dynamically
var img = document.createElement('img');
img.src = 'images/santahat.png';
img.style.width = '50px';
content.appendChild(img);
//Create markers for customer locations and customize
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
map: map,
icon: iconBase + 'homegardenbusiness.png'
});
// Add event listener to open info window and show customer name
marker.addListener('mouseover', function(){
infoWind.setContent(content);
infoWind.open(map, marker);
//add event listener to zoom in to clicked customer
google.maps.event.addListener(marker, 'click', function() {
map.panTo(this.getPosition());
map.setZoom(20);
});
});
})
}
Here is my attempt to add the MarkerClusterer (code same as previous up to this point):
//Create markers for customer locations and customize
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
map: map,
icon: iconBase + 'homegardenbusiness.png'
});
//create marker clusterer to group data
var markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
// Add event listener to open info window and show customer name
marker.addListener('mouseover', function(){
infoWind.setContent(content);
infoWind.open(map, marker);
//add event listener to zoom in to clicked customer
google.maps.event.addListener(marker, 'click', function() {
map.panTo(this.getPosition());
map.setZoom(20);
});
});
markerCluster.addMarker(marker);
})
}
Functioning JS file:
var map;
var geocoder;
//Code to load the map with center point of Monterey MA
function initMap() {
var monterey = {lat: 42.181613, lng: -73.215013};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: monterey,
mapTypeId: google.maps.MapTypeId.HYBRID,
labels: true,
});
//collect customer data and geocoder object - declare geocoder as global
var cusdata = JSON.parse(document.getElementById('data').innerHTML);
geocoder = new google.maps.Geocoder();
codeAddress(cusdata);
var allData = JSON.parse(document.getElementById('allData').innerHTML);
showAllCustomers(allData);
var searchData = JSON.parse(document.getElementById('searchData').innerHTML);
showSearchedCustomer(searchData)
}
function showAllCustomers(allData) {
//declare info window variable outside of loop to allow to clear when selecting other markers
var infoWind = new google.maps.InfoWindow;
//Create marker clusterer to group data
var markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
Array.prototype.forEach.call(allData, function(data){
var content = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = [data.lastName + ' ' + data.physicalAddress];
content.appendChild(strong);
//add image to infowindow - you are also able to add image path to mysql and then append dynamically
var img = document.createElement('img');
img.src = 'images/santahat.png';
img.style.width = '50px';
content.appendChild(img);
//Create markers for customer locations and customize
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
map: map,
icon: iconBase + 'homegardenbusiness.png'
});
markerCluster.addMarker(marker);
// Add event listener to open info window and show customer name
marker.addListener('mouseover', function(){
infoWind.setContent(content);
infoWind.open(map, marker);
//add event listener to zoom in to clicked customer
google.maps.event.addListener(marker, 'click', function() {
map.panTo(this.getPosition());
map.setZoom(20);
});
});
})
}
//google maps geocoding code for address to collect lat lng from customer addresses
function codeAddress(cusdata) {
Array.prototype.forEach.call(cusdata, function(data){
var address = data.lastName + ' ' + data.physicalAddress;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == 'OK') {
map.setCenter(results[0].geometry.location);
//create object that collects the lat and lng data and pass function to update customers lat lng
var points = {};
points.id = data.id;
points.latitude = map.getCenter().lat();
points.longitude = map.getCenter().lng();
updateCustomersWithLatLng(points);
//add code to check the result status from geocode request and if we get an OVER_QUERY_LIMIT error we try again after slight delay // Jay 20201208-1015
} else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function() {
codeAddress(cusdata);
}, 100);
} // else {
// alert("Geocode was not successful for the following reason:"
// + status);
// }
});
});
}
//create update customers function that updates db using ajax call
function updateCustomersWithLatLng(points) {
$.ajax({
url:"action.php",
method:"post",
data: points,
success: function(res) {
console.log(res)
}
})
}
//When search customers is clicked create function to zoom in to the searched customer
function showSearchedCustomer(searchData) {
// var searchedCus = { ? };
// map = new google.maps.Map(document.getElementById("map"), {
// zoom: 20,
// center: searchedCus,
// });
//declare info window vairable outside of loop to allow to clear if selecting other markers
var infoWind = new google.maps.InfoWindow;
Array.prototype.forEach.call(searchData, function(data){
var content = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = [data.lastName + ' ' + data.physicalAddress];
content.appendChild(strong);
//add image to infowindow - you are also able to add image path to mysql and then append dynamically
var img = document.createElement('img');
img.src = 'images/santahat.png';
img.style.width = '50px';
content.appendChild(img);
//Create marker for searched customer location and customize
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
map: map,
icon: iconBase + 'homegardenbusiness.png'
});
// Add event listner to open info window and show customer name
marker.addListener('mouseover', function(){
infoWind.setContent(content);
infoWind.open(map, marker);
});
});
}

Load markers from mysql database and display as markers on Google maps

I am using phonegap and I have a google map which locates the user and places a marker on the map. What I want to do is load markers from a mysql database which holds lat and long details for each place. Do I have to do this through php and ajax? This is the code I have at the moment. Thanks
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Test</title>
<link rel="stylesheet" href="/master.css" type="text/css" media="screen" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript">
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError,{'enableHighAccuracy':false,'timeout':10000});
}
//GEOLOCATION
var onSuccess = function(position) {
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
var myLatlng = new google.maps.LatLng(myLat, myLong);
//MAP
var mapOptions = {
center: new google.maps.LatLng(myLat, myLong),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Hello World!"
});
};
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
</script>
</head>
<body onload="onLoad()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
Define map
var map;
Initialize map:
function initialize(lat,lng, n) { //BY PASSING LATITUDE (lat), LONGITUDE (lng) AND THE TEXT (n) WILL SET A DEFAULT MARKER
var mapOptions = {
scaleControl: true,
center: new google.maps.LatLng(lat, lng),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var marker = new google.maps.Marker({
map: map,
position: map.getCenter()
});
var infowindow = new google.maps.InfoWindow();
infowindow.setContent('<b>ا'+n+'</b>');
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
call this function in device ready function.
You can pass current lat, long-
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
call a ajax request and get location data from server.
Insert all latitude and longitude in locations array within your ajax success request and call setMarkers method
var loc_array = new Array(); //LOCATION ARRAY
$.each(server_response_array, function(i,v){
loc_array[i] = [v.lat, v.lng, v.temp_txt];
}
setMarkers(loc_array);
function setMarkers(locations){
//clearMap();
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker, i
for (i = 0; i < locations.length; i++)
{
var loan = locations[i]['txt'];
var lat = locations[i]['lat'];
var lng = locations[i]['lng'];
latlngset = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
map: map, title: loan , position: latlngset, icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png' //THIS WILL SET A BLUE COLOR MARKER YOU CAN SET MORE COLOR AND ALSO CAN MANAGE FROM DATABASE
});
//map.setCenter(marker.getPosition())
var content = loan;
var infowindow = new google.maps.InfoWindow()
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker,content,infowindow));
}
}
Also see this link
goole-map-javascript-api-unable-to-load-markers-from-mysql-database

Removing marker by latitude/longitude in google maps

I have set of markers in my google map. And at the right side of my map I have list of places marked in the map. Now upon clicking the places the color of the pin/marker should be changed. For this I thought I would delete the marker with latitude and longitude(which I will get on clicking the places link) and place a new marker with new image. But I dont know how to delete a marker with latitude and longitude or by place. Please help.
<script type='text/javascript'>
$(document).ready(function() {
var map = null;
var infowindow = new google.maps.InfoWindow();
function createMarker(place) {
var marker = new google.maps.Marker({
map: map
});
var address = place.formatted_address;
marker.setPosition(place.geometry.location);
marker.setTitle(address);
marker.setVisible(true);
address = address + 'B <a class="link" href="#" title="Want to go" alt="' + address + '">W</a> <a class="link" href="#" alt="' + address + '" title="Favourite">F</a>';
$('#trip_location').append(address);
google.maps.event.addListener(marker, 'click', function(e) {
infowindow.setContent('<div><strong>' + marker.title + '</strong><br>');
infowindow.open(map, marker);
});
google.maps.event.trigger(marker, 'click');
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var input = /** #type {HTMLInputElement} */(document.getElementById('searchTextField'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
input.className = '';
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
var location = place.geometry.location;
var address = place.formatted_address;
createMarker(place);
});
}
$('#trip_location').on('click', '.link', function(e) {
e.preventDefault();
var location = $(this).attr('alt');
});
$('.clear').click(function() {
$('#searchTextField').val('');
});
google.maps.event.addDomListener(window, 'load', initialize);
});
I will be adding multiple markers to google map through google's autocomplete. And the places of the markers will be listed on the right side of the page. When the user clicks the places, it should replace the marker icon.
Instead of deleting and replacing, you could keep a reference to each marker that is associated with a place and just call setIcon on it passing the new setting. See documentation: https://developers.google.com/maps/documentation/javascript/reference#Marker
EDIT: New code in question.
Added markers array to contain the markers, used data attribute to hold marker id, pull markerid attribute value when link element click event is fired.
NOTE: Not tested, so it may be buggy.
$(document).ready(function() {
var map = null;
var markers = [];
var infowindow = new google.maps.InfoWindow();
function createMarker(place) {
var marker = new google.maps.Marker({
map: map
});
var address = place.formatted_address;
marker.setPosition(place.geometry.location);
marker.setTitle(address);
marker.setVisible(true);
markers.push(marker);
address = address + 'W <a class="link" href="#" alt="' + address + '" title="Favourite" data-markerid='" + (markers.length - 1) + "'>F</a>';
$('#trip_location').append(address);
google.maps.event.addListener(marker, 'click', function(e) {
infowindow.setContent('<div><strong>' + marker.title + '</strong><br>');
infowindow.open(map, marker);
});
google.maps.event.trigger(marker, 'click');
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var input = /** #type {HTMLInputElement} */(document.getElementById('searchTextField'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
input.className = '';
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
var location = place.geometry.location;
var address = place.formatted_address;
createMarker(place);
});
}
$('#trip_location').on('click', '.link', function(e) {
e.preventDefault();
var location = $(this).attr('alt');
var markerid = $(this).data('markerid');
var marker = markers[markerid];
});
$('.clear').click(function() {
$('#searchTextField').val('');
});
google.maps.event.addDomListener(window, 'load', initialize);
});

Getting error when trying to pass values from array to Google Maps Object

Im setting some json using wordpress post data on a page and then passing that json to some JS which loops through and adds markers to a map. I'm so close to getting it working, just need to figure out this last part.
My PHP code to create the json from an array:
<script type="text/javascript">
var markers = <?php echo json_encode($pageposts);?>
</script>
Here is my JS code:
var infowindow = null;
$(document).ready(function(){
initialize();
});
function initialize() {
var centerMap = new google.maps.LatLng(41.141208, -73.263726);
var options = {
zoom: 12,
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map'), options);
setMarkers(map, markers);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
}
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i].meta_value),
map: map
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
//infowindow.setContent(this.html);
//infowindow.open(map, this);
});
}
}
If you want to see the page, with the json embedded - check out this link:
http://www.fairfieldctguide.com/test-map
view-source:http://www.fairfieldctguide.com/test-map
Any help would be greatly appreciated!
Jake
google.maps.LatLng expects two numbers as an argument. Currently you are passing in a string which will result in an error. So you need to convert your markers[i].metavalue to two numbers like so:
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
latlng = markers[i].meta_value.split(",")
lat = parseFloat(latlng[0])
lng= parseFloat(latlng[1])
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
//infowindow.setContent(this.html);
//infowindow.open(map, this);
});
}
}
If you don't want to do a converson you could just store lat and lng values as numbers in separate properties. So your json would look like this:
var markers = [{
"ID":"883",
"post_title":"Tucker's Cafe",
"meta_key":"meta_geo",
"lat":41.1674377,
"lng": -73.2236554
}
and you would add a marker like so:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i].lat, markers[i].lng),
map: map
});

how to pull dynamic data from mysql to anguarJS then google map markers

I am trying to pass dynamic data from mysql then creating multiple markers on google.
Here is my html code.
<div ng-app="mapsApp" ng-controller="MapCtrl">
<div class="map">
<div id="map" style="width: 100%;height:738px;"></div>
</div>
</div>
Here is the angularjs Script.
//Angular App Module and Controller
var investup = angular.module('mapsApp', [])
investup.controller('MapCtrl', function ($scope, $compile) {
var cities = [
{
title: 'xyz',
city : '<img src="images/xxx.jpg" />',
lat : 12.2917925,
long : 76.6704174
},
{
title: 'Add to Cart',
city : '<button class="org-btn" ng-click="cartone()" style="display:block;font-size:12px;margin:0 auto 0 auto;">Add to Cart</button>',
lat : 12.2725645,
long : 76.6705986
},
];
//Define your locations: HTML content for the info window, latitude, longitude
var popup = [
['<img src="images/xyz.jpg" />'],
['<img src="images/xyz.jpg"/>'],
];
// Setup the different icons and shadows
var iconURLPrefix = 'http://maps.google.com/mapfiles/ms/icons/';
var icons = [iconURLPrefix + 'red-dot.png', iconURLPrefix + 'purple-dot.png']
var iconsLength = icons.length;
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(12.2982778, 76.6903664),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
streetViewControl: false,
panControl: false,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_BOTTOM
}
}
$scope.popup = popup;
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
var activeInfoWindow;
var activeInfoWindow2;
var iconCounter = 0;
$scope.markers = [];
for (i = 0; i < cities.length; i++) {
var createMarker = function (info) {
var marker = new google.maps.Marker({map: $scope.map,icon: icons[iconCounter],position: new google.maps.LatLng(info.lat, info.long),popup: popup[i][0]});
google.maps.event.addListener(marker, 'click', function() {
if(activeInfoWindow2 != null)
activeInfoWindow2.close();
var contentString = "<div><h2>" + info.city + "</h2></div>";
var compiled = $compile(contentString)($scope);
var infoWindow = new google.maps.InfoWindow({ content: compiled[0] });
infoWindow.open($scope.map, marker);
activeInfoWindow = infoWindow;
});
google.maps.event.addListener(marker, 'mouseover', function() {
var contentString = "<div><h2>" + marker.popup + "</h2></div>";
var compiled = $compile(contentString)($scope);
var infoWindow = new google.maps.InfoWindow({ content: compiled[0] });
infoWindow.open($scope.map, marker);
activeInfoWindow2 = infoWindow;
if(activeInfoWindow != null)
activeInfoWindow.close();
});
google.maps.event.addListener(marker, 'mouseout', function() {
if(activeInfoWindow2 != null)
activeInfoWindow2.close();
});
$scope.markers.push(marker);
}
createMarker(cities[i]);
iconCounter++;
}
$scope.openInfoWindow = function(e, selectedMarker) {
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
}
});
Here is the screenshot of the result
This is the static code when i'm placing php code in cities and popup section to not showing the result.
Problem is when i don't how to call php code in angularJS. Kindly help me.
Thanks in advance.
1- You probably would need to use a framework to handle JSON serialization for you.
For the sake of simplicity you can use this library (https://github.com/mevdschee/php-crud-api), and copy api.php to the server root directory.
2- Using $http:
investup.controller('MapCtrl', function($scope, $compile, $http) {
$http.get('/api.php/cities').success(function(response) {
var cities = response.cities;
// the rest of controller function body
}).catch(handleError);
})

Categories