I want to clear all existing markers from my map when certain ajax call finishes. I will post the API code and my ajax code:
I load my map at the start of the script like so:
<script type="text/javascript">
//SETTINGS
$(document).ready(function() {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
I then do some stuff via ajax and then at the end of the finished ajax call I want to execute clearing of my markers. Look for the comment:
//AJAX AUTOCOMPLETE PLUGIN
var a = $('#searchMap2').autocomplete({
serviceUrl: '/public/index.php/prodajna_mesta/search',
minChars: 1,
delimiter: /(,|;)\s*/, // regex or character
//params: { country:'Yes' }, //aditional parameters
noCache: false, //default is false, set to true to disable caching
// callback function:
onSelect: function(suggestion) {
$.ajax({
url: "/public/index.php/prodajna_mesta/coords",
context: document.body,
data: { coords: suggestion.data }
}).done(function(data) {
//CLEAR MY MARKERS HERE
});
}
});
});
And this is how I initialize google map after all of this:
function initialize() {
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Multiple Markers
var markers = [
<?php foreach ($records as $value): ?>
<?php $records = (array)$records; ?>
['<?php echo $value->name ?>', <?php echo $value->coords ?>],
<?php endforeach; ?>
];
// Info Window Content
var infoWindowContent = [
<?php foreach ($records as $value): ?>
<?php $records = (array)$records; ?>
['<div style="height: 80px; white-space: nowrap;" class="info_content"><b><?php echo $value->name; ?></b><br/><br/><?php echo $value->address; ?><br/>T: <?php echo $value->phone; ?></div>'],
<?php endforeach; ?>
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(9);
google.maps.event.removeListener(boundsListener);
});
}
var mapMarkers = []; Declare it global
push markers to mapMarkers array.
In ajax callback, loop all markers in mapMarkers array and set their map property to null.
clear the mapMarkers array.
var mapMarkers = []; //STEP 1 Global, so that it can be accessed from ajax success callback
function initialize() {
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Multiple Markers
var markers = [
<?php foreach ($records as $value): ?>
<?php $records = (array)$records; ?>
['<?php echo $value->name ?>', <?php echo $value->coords ?>],
<?php endforeach; ?>
];
// Info Window Content
var infoWindowContent = [
<?php foreach ($records as $value): ?>
<?php $records = (array)$records; ?>
['<div style="height: 80px; white-space: nowrap;" class="info_content"><b><?php echo $value->name; ?></b><br/><br/><?php echo $value->address; ?><br/>T: <?php echo $value->phone; ?></div>'],
<?php endforeach; ?>
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
mapMarkers.push(marker); //STEP 2
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(9);
google.maps.event.removeListener(boundsListener);
});
}
//AJAX AUTOCOMPLETE PLUGIN
var a = $('#searchMap2').autocomplete({
serviceUrl: '/public/index.php/prodajna_mesta/search',
minChars: 1,
delimiter: /(,|;)\s*/, // regex or character
//params: { country:'Yes' }, //aditional parameters
noCache: false, //default is false, set to true to disable caching
// callback function:
onSelect: function(suggestion) {
$.ajax({
url: "/public/index.php/prodajna_mesta/coords",
context: document.body,
data: { coords: suggestion.data }
}).done(function(data) {
//CLEAR MY MARKERS HERE
//STEP 3
var len = mapMarkers.length;
for(var i=0; i<len; i++){
mapMarkers[i].setMap(null);
}
mapMarkers = []; //Empty the array
});
}
});
});
Related
I am using google map api with contain location function .... i am retrieving latitude longitude from database i am using foreach loop to get result.If marker is within polygon it will stop foreach but problem it is not showing any result. Result come out is from last row query how can i fix it.It is showing me only last row from database .Below is my code
<?php
if(!empty($zone)){
foreach($zone as $findzone)
{
$exploded_data=explode('),',$findzone['zone_latlog']);
$count=count($exploded_data);
?>
<script>
var latitude = document.getElementById('latitude').value;
var longitude = document.getElementById('longitude').value;
var map;
var coord1 = new google.maps.LatLng(latitude, longitude);
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(33.714760, 73.083160),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bermudaTriangle = new google.maps.Polygon({
map: map,
paths: [
<?php
for($i=0;$i<$count;$i++){
echo "new google.maps.LatLng".$exploded_data[$i]."),";
}
?>
]
});
var bounds = new google.maps.LatLngBounds();
for (var i=0; i<bermudaTriangle.getPath().getLength(); i++) {
bounds.extend(bermudaTriangle.getPath().getAt(i));
}
bounds.extend(coord1);
var marker1 = new google.maps.Marker({
map: map,
position: coord1
});
map.setCenter(bounds.getCenter());
map.setZoom(11);
checkInPolygon(marker1, bermudaTriangle);
}
google.maps.event.addDomListener(window, "load", initialize);
function checkInPolygon(marker, polygon) {
var infowindow = new google.maps.InfoWindow();
var html = "";
if (google.maps.geometry.poly.containsLocation(marker.getPosition(), polygon)) {
html = "inside polygon";
} else {
html = "outside polygon";
}
infowindow.setContent(html);
infowindow.open(map, marker);
}
</script>
<?php
}}?>
How to fix that problem that show me only only that polygon that has my latitude longitude marker
I am working on a wordpress site that will use a google map api, but i encounter a problem by adding rating widget in the google map infowindow. The rating criteria is showing but not the star.
Here is the screenshot
and here is my code
<script type="text/javascript">
jQuery(function($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
});
function initialize() {
var map, casino_name, lat, longt ;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Multiple Markers
var markers = [
//[casino_name, lat, longt],
<?php
$tooltip = '';
$args = array(
'post_type' => 'page',
'post_parent' => get_the_ID(),
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$post_id = get_the_ID();
echo "['".$casino_name = get_field('casino_name', $post_id)."', ".get_field('latitude', $post_id).', '.get_field('longitude', $post_id).']';
$rating = do_shortcode('[ratingwidget type="page" post_id='.get_the_ID().']');
$tooltip .= "['".'<img src="'.get_field('casino_logo', $post_id).'" alt=""/>'." ".'<a class="casino-link" href="'.get_field('casino_link', $post_id).'">'.get_field('casino_name', $post_id).'</a>'." ".$rating."']";
if (($the_query->current_post +1) != ($the_query->post_count)){
echo ',';
$tooltip .= ',';
}
wp_reset_postdata();
}
}
/* Restore original Post Data */
wp_reset_postdata();
?>
];
// Info Window Content
var infoWindowContent = [
<?php echo $tooltip; ?>
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow();
var marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
console.log(infoWindow);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
}
</script>
To implement Info Box instead of the standard Info Window, first add the InfoBox JS to your site.
Set the options for your Info Box based on the list of options in the properties table at the bottom of this page.
Here's a quick example, these options can go anywhere in your maps code:
// Set infobox options
var boxOptions = {
boxClass: "box-styles", /* Applies a class to your box for styling */
zIndex: 9999,
boxStyle: {
opacity: 0.75,
width: "222px"
},
closeBoxMargin: "10px",
closeBoxURL: "/assets/img/icons/cancel.png",
}
Then in your code, just replace:
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow();
With:
// Display multiple markers on a map
var infoBox = new InfoBox(boxOptions);
Then replace each instance of InfoWindow() with InfoBox() in your click event like so:
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoBox.setContent(infoWindowContent[i][0]);
infoBox.open(map, marker);
console.log(infoBox);
}
})(marker, i));
The above should give a rough idea of how to implement this. If your still having trouble - I suggest you create a fiddle with your code and work from that. Hope this helps.
Also have a look at the examples here: http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/docs/examples.html
I am using gmap3 plugin to show google map. In my case I have stored all the information of properties in the database(mysql) with custom markers. Now I want that when the page is loaded it will display all the markers in google map.
For loading googlemap with gmap3 plugin I am using this code
function loadMap() {
jQuery(document).ready(function(){
if(typeof gMap == 'undefined') {
//// CREATES A MAP
gMap = jQuery('#map-canvas');
gMap.gmap3({
map: {
options: {
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
scrollwheel: true,
streetViewControl: false
}
}
});
}
});
}
and inside div ``map-canvas I can see the map. But can some one kindly tell me how to show all the markers with the positions? Any help and suggestions will be really appreciable. Thanks.
Update
If I am wrong with my codes then someone can show their codes to me. I am using Gmap3 plugin.
I am not sure about this it will work in gmap3 but i use this code for creating my costome icon hope it will help you
In the index.php use this for creating your costom icon pathlike this
<?php
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
$a=array();
while ($row = #mysql_fetch_assoc($result)){ $a='$row[\'type\']'=>array('icon'=>'$row[\'path\']','shadow'=>'$row[\'path2\']')
}
$a=json_encode($a);
?>
it should be done before js file after that
write this
<script>
var customIcons= <?php echo $a; ?>;
</script>
and finally load your map and infoWindowbox() in that function
function infoWindowbox() {
downloadUrl("xml.php", 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,
animation: google.maps.Animation.DROP
});
markerArray.push(marker);
bounds.extend(marker.position);
bindInfoWindow(marker, map, infoWindow, html);
}
map.fitBounds(bounds);
// var markerCluster = new MarkerClusterer(map, markerArray);
});
}
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() {}
gmap3 initializator has a marker attribute that allows you to create markers.
See example with single and multiple markers here:
http://gmap3.net/en/catalog/10-overlays/marker-41
I think this example might help.
Updated:
If you want to read the data like from database (or) xml, You can then make an ajax request to that page (from any page on your site) using jQuery:
I have an example but this is with xml to get the data from xml file.
$.ajax({
url: 'categories.xml (or) your database path',
type: 'get',
success: function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new GLatLng(lat,lng);
var address = markers[i].getAttribute("address");
var name = markers[i].getAttribute("name");
var html = "<b>"+name+"<\/b><p>"+address;
var category = markers[i].getAttribute("category");
// create the marker
var marker = createMarker(point,name,html,category);
map.addOverlay(marker);
}
// == show or hide the categories initially ==
show("theatre");
hide("golf");
hide("info");
// == create the initial sidebar ==
makeSidebar();
});
});
Like this you may get the data from database also through using queries. Try this one atleast you may get the idea.
The gmaps3 plugin documentation shows how to add markers. If you create an options array in php through ajax/json and feed that to the markers: option your markers should be added.
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
});
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);
})