I am currently working on ionic native google maps building weather map . Basically i want to get LatLngBounds and zoom level while camera move then pass those data to url even shows data on map .
example every time when move map and zoom level, the url dynamically updates .
http://www.xxxxxxxx.net/map#lat=-25.87899&lng=-42.45117&zoom=4
My code :
getData(){
////Here should pass LatLngBounds in url ////
this.http.get('xxxxxxx/MetarJSON.php?bbox='','','',''' ,{},{}).then(data=>{
let DataJson = JSON.parse(data.data)
for (let datas of DataJson['features']) {
this.points.push({ lng: datas.geometry.coordinates[0], lat: datas.geometry.coordinates[1] });
}
for (let i = 0; i < DataJson.features.length; i++) {
let coords = DataJson.features[i].geometry.coordinates;
this.latLng = new LatLng(coords[1], coords[0]);
this.icoa = DataJson.features[i].properties.id
this.rawOb = DataJson.features[i].properties.rawOb
let fltcat = DataJson.features[i].properties.fltcat
let marker: Marker = this.map.addMarkerSync({
position: this.latLng,
title:fltcat,
icon: icons
})
}
})
}
loadMap() {
let mapOptions: GoogleMapOptions = {
camera: {
target: {
lat: 33.263,
lng: 44.232
},
zoom: 6,
}
};
this.map = GoogleMaps.create('map_canvas', mapOptions);
//// Here l get LatLngBounds but when l move map the lat and lng aren't update
let chec1= this.map.getVisibleRegion().farLeft.lat
let chec2= this.map.getVisibleRegion().farLeft.lng
console.log(chec1,chec2)
}
Ionic Google map native plugin Doc
l found solution while move map to update LatLngBounds . used GoogleMapsEvent constants
depending on doc , and he is working fine
this.map.on(GoogleMapsEvent.CAMERA_MOVE).subscribe(()=>{
let left= this.map.getVisibleRegion().northeast.lat
let leftbottom= this.map.getVisibleRegion().northeast.lng
let right= this.map.getVisibleRegion().southwest.lat
let rightbottom= this.map.getVisibleRegion().southwest.lng
console.log(left,leftbottom , right ,rightbottom )
})
Related
I want to display on my webpage the location from a JSON that has displayed a pharmacy name. The point is that google maps API is a little bit over my power of knowledge. I did a find-place request into the google maps API, but the location that is displayed is the one from my current location.
Here is the part of the code that would interest you
<div id="map"></div>
<script src="./keys.js"></script>
<script>
let map;
document.addEventListener("DOMContentLoaded", () => {
let s = document.createElement("script");
document.head.appendChild(s);
s.addEventListener("load", () =>
{
console.log("script has loaded");
x = navigator.geolocation;
x.getCurrentPosition(success, failure)
function success(position){
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
var coords = new google.maps.LatLng(myLat,myLong);
map = new google.maps.Map(document.getElementById("map"), {
center: coords,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
map: map,
position: coords,
})
}
function failure(){}
});
s.src = `https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=<%= "#{#medicament['farmacies'].first['name']}"%>&inputtype=textquery&fields=formatted_address,name,rating,opening_hours,geometry&key=**************`;
});
</script>
</div>
where <%= "#{#medicament['farmacies'].first['name']}"%> represents the name of the pharmacy from the html erb file.
What I found strange is that if I inspect the page where the location is the s.src takes me to a JSON that has all the right address information for the pharmacy.
Here you can see an image with the response from the API:
What I want is to point to the address of that pharmacy on google map. Any tips&tricks are very welcome!
Use google.maps.places.PlacesService.findPlaceFromQueryinstead.
Also see this tutorial.
var service = new google.maps.places.PlacesService();
var request = {
query: 'Museum of Contemporary Art Australia',
fields: ['name', 'geometry'],
};
const {results} = service.findPlaceFromQuery(request);
I have a Google Map with a set of markers on. I'm trying to add MarkerClusterer to it to simplify the view. Overall, doing so should be pretty easy from what I've seen online but when I try it, my map doesn't show any markers, clusters or anything. My code is below:
function calculateCenter() {
center = map.getCenter()
}
let center
let worldCenter = new window.google.maps.LatLng(32.249974, 5.800781)
let mapOptions = {
center: worldCenter,
zoom: 3,
scrollwheel: false
}
let map = new google.maps.Map(document.querySelector('.banner--map--parks'), mapOptions)
let infoWindow = new google.maps.InfoWindow()
let markers = []
map.addListener('idle', _ => {
calculateCenter()
})
fetch('/api/parks.json')
.then(response => response.json())
.then(data => {
data.forEach(park => {
if (park.lat && park.lng) {
let title = park.name
let position = new google.maps.LatLng(park.lat, park.lng)
let icon = 'https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_blue.png'
let marker = new google.maps.Marker({
position: position
title: title,
icon: icon,
// map: map
})
let parkIWContent = '<div class="iw">' + park.name + '</div>'
marker.addListener('click', (function(marker, parkIWContent) {
return function() {
infoWindow.setContent(parkIWContent);
infoWindow.open(map, marker);
// map.panTo(new google.maps.LatLng(park.lat, park.lng))
};
})(marker, parkIWContent))
markers.push(marker)
}
})
})
console.log(markers)
let markerCluster = new MarkerClusterer(map, markers)
map.addListener("click", _ => {
infoWindow.close()
})
As you can see, at one point I did output the array of markers and they do all show up in the console but still fail to show on the map.
Can anyone spot any issues with the code that may be causing this?
Thanks
I've actually managed to solve this. I needed to move the Marker Clusterer inside the .then in order for it to work.
I follow this guide
https://developers.google.com/maps/documentation/javascript/places#places_photos
to create place photo as marker icon. This is my map initialization code:
var map;
function initMap() {
// Create a map centered in Pyrmont, Sydney (Australia).
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -6.920812, lng: 107.604116},
zoom: 13
});
var request = {
location: map.getCenter(),
radius: '5000',
type: ['shopping_mall']
};
var service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
}
// Checks that the PlacesServiceStatus is OK, and adds a marker
// using the place ID and location from the PlacesService.
function callback(results, status) {
console.log(results);
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createPhotoMarker(place);
}
}
}
google.maps.event.addDomListener(window, 'load', initMap);
this is the createPhotoMarker function
function createPhotoMarker(place) {
var photos = place.photos;
if (!photos) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
title: place.name
});
return;
}
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
title: place.name,
icon: photos[0].getUrl({'maxWidth': 35, 'maxHeight': 35})
});
}
the function will create regular marker if place photo is not available. But for the place with photo available, I get this error :
Failed to load resource: the server responded with a status of 404 () lh3.googleusercontent.com/w35-h35-p/AF1QipOIL6GVVmtqp_cw_hBEQxdILZSa8poMO0HAqFHd=k
And the map only shows regular marker.
What did I do wrong?
This is the fiddle http://jsfiddle.net/v90fmrhp/
==========Update 2017-07-07============
Thanks for the answers and fixes
It seems the issue solved. My fiddle is working now
https://issuetracker.google.com/issues/63298126
Marked as Fixed
Good news! We have fixed this issue. Thanks for your patience.
Happy Mapping!
Looks like the error you are seeing is caused by some issue on Google's side. It's affecting quite a few other users as well, have a look at their public issue tracker:
Thanks for reporting this issue. We verified it and we'll keep tracking it.
https://issuetracker.google.com/issues/63298126
UPDATE (2017-07-06):
A fix for this is going into our release process now and it should be out soon - probably Monday at the latest.
https://issuetracker.google.com/issues/63298126#comment13
Had the same issue and Sulyman suggested a workaround that is working but I don't know for how long when google fixes this.
Google Places Photos .GetUrl is adding width and height to url
Here is what we did.
if(place.photos != null){
for(var i = 0; i < place.photos.length; i++){
//Do a string replace to get the w-h-p out of there.
var str = place.photos[i].getUrl({"maxWidth": 100, "maxHeight": 100});
var res = str.replace("w100-h100-p", "p");
self.pacPhotos.push({
id : res
});
}
}else {
console.log("no photo");
}
}
I also ran into this with google places api. Everything was working fine then randomly it stopped. It seems likely that it is due to google making changes as they get ready for releasing a better maps api to support vector
#DKinnison saved me with his solution so I just wanted to post my ES6 solution for parsing a received place. I commented out the other properties I am personally not using in case you need to.
const PHOTO_WIDTH = 600;
const PHOTO_HEIGHT = 600;
export function parseGooglePlace(place) {
if (!place) {
return;
}
const {
// address_components,
formatted_address,
geometry,
// icon,
// id,
// international_phone_number,
name,
// rating,
// reviews,
// opening_hours,
photos: _photos = [],
place_id,
// reference,
types = [],
// url: mapsURL,
// utc_offset,
// vicinity,
website,
} = place;
const photos = _photos.map(p =>
p
.getUrl({ maxWidth: PHOTO_WIDTH, maxHeight: PHOTO_HEIGHT })
.replace(`w${PHOTO_WIDTH}-h${PHOTO_HEIGHT}-p`, 'p'),
);
return {
website,
name,
photos,
address: formatted_address,
placeId: place_id,
geometry,
types,
};
}
I am following the Josh morony's tutorial and
trying to get the bounds information of google map.
But the outcome of getBounds() is "undefined"
How can I get the value of getBounds()?
My developing environment is
"Ionic2 (2.0.0-rc.4) + typescript"
And my code is like below
initMap(): Promise<any> {
this.mapInitialised = true;
return new Promise((resolve) => {
let latLng = new google.maps.LatLng(37.481223, 126.952701);
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement, mapOptions);
let bounds = this.map.getBounds();
console.log(bounds); <-- output "undefined"
resolve(true);
});
}
Thanks in advance ! :)
Try this one :)
this.map.getBounds().getSouthWest().lat(),
this.map.getBounds().getNorthEast().lat(),
this.map.getBounds().getSouthWest().lng(),
this.map.getBounds().getNorthEast().lng()
Ensure that your map is initialized and tiles loaded by listening for the tilesloaded event. This code example would output Latitude and Longitude values for and map bounds change such as panning or zooming.
google.maps.event.addListener(this.map, 'tilesloaded', () => {
console.log(this.map.getBounds().getNorthEast().lat());
console.log(this.map.getBounds().getNorthEast().lng());
console.log(this.map.getBounds().getSouthWest().lat());
console.log(this.map.getBounds().getSouthWest().lng());
});
I am using Drupal 7 - Location, GMap module. I have a view that renders the result in a gmap. Everything works fine here and I get all the markers. Now I need a Find My location button which shows the users current location and adds a marker to the existing map.
Google Map Api V3 always works on a newly created map and I couldn't find a function which returns an existing map in the current page.
Gmap module provides a JS function - Drupal.gmap.getMap('ur-map-id') which is supposed to return a pointer to the map whose id is given. But this did not work.
Could someone please guide me as to how I should go about this? Can I get it work with Google Maps API? I need to retain the original map with all its markers.
Here's something for reference.
if (typeof(navigator.geolocation) !== 'undefined') {
var showUserOnMap = function(position) {
var map = Drupal.gmap.getMap('gmap-auto1map-gmap0');
if (typeof(map) !== 'undefined' && map !== false) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
var marker = {
latitude: latitude,
longitude: longitude,
markername: Drupal.t('You'),
opts: {
title: Drupal.t('You')
}
}
marker.opts.position = new google.maps.LatLng(latitude, longitude);
marker.opts.map = map.map;
Drupal.gmap.factory.marker(marker.opts);
}
};
// Get the current location
navigator.geolocation.getCurrentPosition(showUserOnMap);
}
I am having this issue as well, you can put this jquery code in for it to actually centre around your current location - but no marker is added. Just add it anywhere in your theme,
jQuery(document).ready(function() {
jQuery(function($) {
$.extend({
initialize: function () {
var m = Drupal.gmap.getMap('auto1map');
if (m.map && m.markersready) {
$.setCoords();
}
else {
m.bind('markersready', function(data) {
$.setCoords();
});
}
},
setCoords: function () {
navigator.geolocation.getCurrentPosition(function (position) {
var gmap = Drupal.gmap.getMap('auto1map').map;
var lat = position.coords.latitude;
var lng = position.coords.longitude;
gmap.setCenter(new google.maps.LatLng(lat, lng));
gmap.setZoom(13);
});
}
});
$.initialize();
});
});
Now you can centre your map around your location and now I need to figure out a way to place a marker down at this location.