Google Map Update dynamically in Angular - angularjs

http://plnkr.co/edit/Zd9GwG?p=preview
I am working on this google map + angular.js example . I want to change the location center dynamically depend on the variable .i.e. I want to make it dynamic center. Please suggest how to do this ?
I want to do some thing Like this.
// Code goes here
//Add the requried module 'angular-ui' as a dependency
angular.module('maptesting', ['ui.directives']);
function MapCtrl($scope) {
$scope.lat = 35.120922 ;
$scope.long = -89.97731 ;
var ll = new google.maps.LatLng($scope.lat, $scope.long);
$scope.mapOptions = {
center: ll,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Markers should be added after map is loaded
$scope.onMapIdle = function() {
//alert("DF");
if ($scope.myMarkers === undefined){
var marker = new google.maps.Marker({
map: $scope.myMap,
position: ll
});
$scope.myMarkers = [marker, ];
}
};
$scope.showMarkerInfo = function(marker) {
$scope.myInfoWindow.open($scope.myMap, marker);
};
$scope.changeval = function(){
$scope.lat = 13.0810 ;
$scope.long = 80.2740 ;
};
}

You need to watch for changes in the scope in order to refresh the map.
Demo Plunkr
(just use the input fields above the map to change the center of the map in real time)
The important part is $scope.$watch:
var updateCenter = function() {
var ll = new google.maps.LatLng($scope.lat, $scope.long);
$scope.myMap.panTo(ll);
// eventually more stuff
}
$scope.$watch('lat', updateCenter);
$scope.$watch('long', updateCenter);

Related

Add custom marker with store logo in ionic using google map

I am working with ionic and i want to display map marker with store logo. I constructed a default marker and I have lots of store pics or logos which need to be placed within the marker show in above image. I have used cordova geolocation plugin for get current location of user.
Response array like this :
var markers = [{
storeName: "Dib Dab Extract",
profilePic: "img/dibdab.png",
address: "420 Mary Jane Way",
rating: "4",
reviews: "4379",
offer: "100 Free Coins with 1st Purchse",
lat: "53.896408",
long: "-105.991427"
}]
Custom Marker Icon :
var image = {
url: 'img/ic_map_pin_gray.png', // image is 512 x 512
scaledSize: new google.maps.Size(80, 80),
};
Marker set on map like this :
var markerPos = new google.maps.LatLng(record.lat, record.long);
// Add the markerto the map
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: markerPos,
icon: image,
});
Issue is resolved using Custom Marker. I have done code like this and i get exact marker like i want in above question. So i posted this answer that help anyone who want custom marker like this. i have refer https://humaan.com/blog/custom-html-markers-google-maps/
// Map Initilize function
function initMap() {
var options = {
timeout: 10000,
enableHighAccuracy: true
};
$cordovaGeolocation.getCurrentPosition(options).then(function(position) {
var latLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: 15,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
//Wait until the map is loaded
//Load the markers
loadMarkers();
//});
}, function(error) {
console.log(error);
console.log("Could not get location");
//Load the markers
loadMarkers();
});
}
//load marker using rest api
function loadMarkers() {
CommonService.ShowLoader();
YOUR REST API SERVICE.then(function(res) {
angular.forEach(res, function(value, key) {
var record = value;
console.log(record);
var image = {
url: 'img/ic_map_pin_gray.png', // custom background image (marker pin)
scaledSize: new google.maps.Size(70, 70),
};
var markerPos = new google.maps.LatLng(record.lat, record.long);
//Add the markerto the map
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: markerPos,
icon: image,
});
var img_src = record.profilePic;
var overlay = new CustomMarker(
markerPos,
map, {image: img_src}
);
});
}).catch(function(error, status, headers, config) {
console.log(error);
});
}
//CustomMarker function
function CustomMarker(latlng, map, args) {
this.latlng = latlng;
this.args = args;
this.setMap(map);
}
CustomMarker.prototype = new google.maps.OverlayView();
CustomMarker.prototype.draw = function() {
var self = this;
var div = this.div;
if (!div) {
div = this.div = document.createElement('img');
div.src = self.args.image;
div.className = 'marker';
div.style.position = 'absolute';
div.style.cursor = 'pointer';
div.style.width = '35px';
div.style.height = '35px';
div.style.borderRadius = '50%';
if (typeof(self.args.marker_id) !== 'undefined') {
div.dataset.marker_id = self.args.marker_id;
}
google.maps.event.addDomListener(div, "click", function(event) {
google.maps.event.trigger(self, "click");
});
var panes = this.getPanes();
panes.overlayImage.appendChild(div);
}
var point = this.getProjection().fromLatLngToDivPixel(this.latlng);
if (point) {
div.style.left = (point.x - 18) + 'px'; // set custom (i set it as i want to set in map )
div.style.top = (point.y - 56) + 'px'; //set custom (i set it as i want to set in map )
}
};
This worked for me.
marker = new MarkerWithLabel({
position: new google.maps.LatLng(item.latitude, item.longitude),
animation: google.maps.Animation.DROP,
labelContent: "My Job Location",
labelAnchor: new google.maps.Point(10, 38),
labelClass: "markLabelsJob", // the CSS class for the label
labelInBackground: false,
icon: 'img/active-job-pin.png',
map: map
});

How many markers can I import from .js file?

I'm trying to import markers from .js file into my Google Maps.
I use Google Maps Javascript API v3.
If the .js file has too many markers, the map doesn't show any marker.
When I delete some markers in .js file, the map shows all markers from .js file.
What's wrong with this?
I want to import 1,000 ~ 3,000 markers from .js file and show the markers only in the visible bound on the map.
Is there any limitation of the markers while reading .js file?
I don't use JQuery, node.js.
Do I have to callback function? Please help me.
Thanks in advance.
a.html
...
<script src="js/markers.js"></script>
...
<script type="text/javascript">
var mymap; // one map
...
function showMarker(eachLocations) {
// get the center of the map and zoom level
var new_center = mymap.getCenter();
defaultLat = new_center.lat();
defaultLon = new_center.lng();
var zoomLevel = mymap.getZoom();
var marker,i;
var pin_image_url = "/common/images/marker_img.png";
var myMarkerIcon;
var bounds = mymap.getBounds();
var ne = bounds.getNorthEast(); // LatLng of the north-east corner
var sw = bounds.getSouthWest(); // LatLng of the south-west corder
var nw = new google.maps.LatLng(ne.lat(), sw.lng());
var se = new google.maps.LatLng(sw.lat(), ne.lng());
// for each location
for (i = 0; i < eachLocations.length; i++) {
// custom marker
myMarkerIcon = new
google.maps.MarkerImage(pin_image_url,null,null,null,new
google.maps.Size(32,37));
if (eachLocations[i][1] >= se.lat() && eachLocations[i][1] <= nw.lat() && eachLocations[i][2] >= nw.lng() && eachLocations[i][2] <= se.lng()) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(eachLocations[i][1], eachLocations[i][2]),
map: mymap,
icon: myMarkerIcon
});
markers.push(marker);
// listner for marker
google.maps.event.addListener(marker, 'click', (function(marker, i) {
// click,dblclick,mouseup,mousedown,mouseout
return function() {
// if any infowindow has already shown, hides it and shows the new one
if (infowindow) infowindow.close();
// make the infoWindow of the first marker
infowindow = new google.maps.InfoWindow({
map: mymap,
position: new google.maps.LatLng(eachLocations[i][1], eachLocations[i][2])
});
infowindow.setContent('<div style="width:250px;text-align: center;font-size:10pt;font-family:Arial,Verdana;font-weight:bold";>'+eachLocations[i][0]+'</div>');
infowindow.open(mymap, marker);
}
})(marker, i));
} // end of if the location is in the bounds
} // end of for each locations
} // end of function
function initialize() {
var mapDiv=document.getElementById("mapholder");
var myOptions={
center:new google.maps.LatLng(defaultLat,defaultLon),
zoom:defaultZoomLevel,
mapTypeId:google.maps.MapTypeId.ROADMAP,
zoomControl: true, // by default
zoomControlOptions: {style: google.maps.ZoomControlStyle.LARGE},
mapTypeControl:false,
navigationControlOptions:
{style:google.maps.NavigationControlStyle.SMALL}
};
// make map instance
mymap=new google.maps.Map(mapDiv,myOptions);
// Create the DIV to hold the control and
// call the CenterControl() constructor passing in this DIV
var centerControlDiv = document.createElement('div');
var centerControl = new CenterControl(centerControlDiv, mymap);
centerControlDiv.index = 1;
mymap.controls[google.maps.ControlPosition.BOTTOM_LEFT].push( centerControlDiv);
getLocation();
google.maps.event.addListener(mymap, 'idle', function(ev){
var new_center = mymap.getCenter();
defaultLat = new_center.lat();
defaultLon = new_center.lng();
// you may have too many markers problem
// so, before sending array, you have to rearrange markers to show
var bounds = mymap.getBounds();
var ne = bounds.getNorthEast(); // LatLng of the north-east corner
var sw = bounds.getSouthWest(); // LatLng of the south-west corder
var nw = new google.maps.LatLng(ne.lat(), sw.lng());
var se = new google.maps.LatLng(sw.lat(), ne.lng());
var markers2show = [];
var lengthofarray = myLocations.length;
for (i=0;i<myLocations.length;i++) {
// limit the markers for the new bound
if (myLocations[i][1] >= se.lat() && myLocations[i][1] <= nw.lat() && myLocations[i][2] >= nw.lng() && myLocations[i][2] <= se.lng()) {
markers2show.push(myLocations[i]);
}
}
showMarker(markers2show);
});
// close the previous info window of marker when click the map
google.maps.event.addListener(mymap, 'click', function() {
infowindow.close();
});
showMarker(myLocations);
}
...
<body onload="initialize()">
...
js/markers.js
var myLocations = [
['A Location',37.007756,140.750864],
['B Location',37.111598,140.424843],
['C Location',36.881268,140.025215]
];

ui-map google is not defined

like the title says when i try to use ui-map module i receive that error.
I have try to use this sample http://jsfiddle.net/sjmcpherso/9kF7d/
on my pc, i have add to the dependencies ui-map and ui-event too, but when i start the application the console log say google is not defined, more precisly at the fifth row of my code
that's my code
http://jsfiddle.net/Lw9XW/
//Add the requried module 'angular-ui' as a dependency
angular.module('maptesting', ['ui.event','ui.map','ui.directives']);
function MapCtrl($scope) {
var ll = new google.maps.LatLng(13.0810, 80.2740);
$scope.mapOptions = {
center: ll,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Markers should be added after map is loaded
$scope.onMapIdle = function() {
if ($scope.myMarkers === undefined){
var marker = new google.maps.Marker({
map: $scope.myMap,
position: ll
});
$scope.myMarkers = [marker, ];
}
};
$scope.showMarkerInfo = function(marker) {
$scope.myInfoWindow.open($scope.myMap, marker);
};

Adding XML attributes to GMap3 infoBubbles

Although I got this working in Gmapv2..version three is proving to be a little trickier.
I wanted to add the other attributes into the infobubble from the XML file, but whereever I try and add them, it breaks the on-click marker?
<script type="text/javascript">
var infowindow;
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(54.046575, -2.8007399);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("http://www.xxxxxx.com/xxxxx.com/server/venue_output.php", function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("latitude")),
parseFloat(markers[i].getAttribute("longitude")));
var event_name = markers[i].getAttribute("event_title");
var event_start = markers[i].getAttribute("event_start");
var event_link = markers[i].getAttribute("event_link");
var marker = createMarker(markers[i].getAttribute("event_name"),latlng);
}
});
}
function createMarker(name, latlng) {
var marker = new google.maps.Marker({position: latlng, map: map, bounce:true, icon : new google.maps.MarkerImage('http://www.gigizmo.com/gigizmo.com/app/images/marker.png')});
google.maps.event.addListener(marker, "click", function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: "<b>" + name + "</b>" });
infowindow.open(map, marker);
});
return marker;
}
</script>
How do I add my javascript values such as event_link to this marker window?
infowindow = new google.maps.InfoWindow({content: "<b>" + name + "</b>" });
You may try this code snippet, provided at : this example
function createMarker(..){
eval(" infowindow"+time+" = new google.maps.InfoWindow({ content: pt.latLng.toString() });");
eval(" marker"+time+" = new google.maps.Marker({ position: pt.latLng, map: map });");
eval(" google.maps.event.addListener(marker"+time+", \"click\", function() { infowindow"+time+".open(map, marker"+time+"); });");
time++;
//rest of your code
}
And also, speaking of my previous experiences:
be sure that your XML file does not include linebreaks.
Especially as the value you set to "name" variable.

Google maps Info Window Overlay content just like that in maps.goole.com

I want have the info window content for a marker just a s below
My code so far is
loadEmbeddedMap : function() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initEmbeddedMap";
document.body.appendChild(script)
},
initEmbeddedMap : function() {
var myLatlng = new google.maps.LatLng(40, -80);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("embeddedGoogleMap"), myOptions);
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': $('#userMapAddress').val()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
console.debug(results[0]);
infowindow = new google.maps.InfoWindow();
var infoWindowContent = "<div><strong>Address:</strong></div>";
infoWindowContent += "<div>"+results[0].address_components[0].short_name+","+results[0].address_components[1].short_name+"</div>";
infoWindowContent += "<div>"+results[0].address_components[5].short_name+","+results[0].address_components[7].short_name+"</div>";
//infoWindowContent += results[0].formatted_address;
infowindow.setContent(infoWindowContent);
infowindow.open(map, marker);
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
$('#embeddedGoogleMapWrapper').show();
},
Code above outputs this
How to get those 'Directions', 'Search near by' stuffs..? Any helps appreciated..
I would start by reading
http://code.google.com/apis/maps/documentation/localsearch/devguide.html#hiworld
As i can see it is possible to do what you want. I cant get you a straight answer but maybe a clue.
I would create my own form in infowindow at least pretty close to the original google one and handle click events by sending those search queries.
Than you need to handle search results
http://code.google.com/apis/maps/documentation/localsearch/devguide.html#handle_search_results
Do some testing with
http://code.google.com/apis/ajax/playground/#the_hello_world_of_local_search
For example you can get lat from localSearch.results[i].lat and so on.
I hope you can get something out of this

Resources