У меня есть карта, на которой я пока не использую геолокацию. Теперь, когда у меня есть SSL на моем веб-сайте, я добавил его в соответствии с документацией Google Maps API. Проблема, однако, в том, что теперь я получаю метку в качестве маркера и не могу понять, как вернуть ее на свой собственный.

Может ли кто-нибудь помочь и объяснить как?

Мой код:

var marker;

function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom : 13,
        center : {
            lat : 59.909144,
            lng : 10.7436936
        },
        disableDefaultUI : true,

        //START STYLE
        styles : [{
                "elementType" : "geometry",
                "stylers" : [{
                        "color" : "#ebe3cd"
                    }
                ]
            }, {
                "elementType" : "labels.text.fill",
                "stylers" : [{
                        "color" : "#523735"
                    }
                ]
            }, {
                "elementType" : "labels.text.stroke",
                "stylers" : [{
                        "color" : "#f5f1e6"
                    }
                ]
            }, {
                "featureType" : "administrative",
                "elementType" : "geometry.stroke",
                "stylers" : [{
                        "color" : "#c9b2a6"
                    }
                ]
            }, {
                "featureType" : "administrative.land_parcel",
                "elementType" : "geometry.stroke",
                "stylers" : [{
                        "color" : "#dcd2be"
                    }
                ]
            }, {
                "featureType" : "administrative.land_parcel",
                "elementType" : "labels.text.fill",
                "stylers" : [{
                        "color" : "#ae9e90"
                    }
                ]
            }, {
                "featureType" : "landscape.natural",
                "elementType" : "geometry",
                "stylers" : [{
                        "color" : "#dfd2ae"
                    }
                ]
            }, {
                "featureType" : "poi",
                "elementType" : "geometry",
                "stylers" : [{
                        "color" : "#dfd2ae"
                    }
                ]
            }, {
                "featureType" : "poi",
                "elementType" : "labels.text.fill",
                "stylers" : [{
                        "color" : "#93817c"
                    }
                ]
            }, {
                "featureType" : "poi.park",
                "elementType" : "geometry.fill",
                "stylers" : [{
                        "color" : "#a5b076"
                    }
                ]
            }, {
                "featureType" : "poi.park",
                "elementType" : "labels.text.fill",
                "stylers" : [{
                        "color" : "#447530"
                    }
                ]
            }, {
                "featureType" : "road",
                "elementType" : "geometry",
                "stylers" : [{
                        "color" : "#f5f1e6"
                    }
                ]
            }, {
                "featureType" : "road.arterial",
                "elementType" : "geometry",
                "stylers" : [{
                        "color" : "#fdfcf8"
                    }
                ]
            }, {
                "featureType" : "road.highway",
                "elementType" : "geometry",
                "stylers" : [{
                        "color" : "#f8c967"
                    }
                ]
            }, {
                "featureType" : "road.highway",
                "elementType" : "geometry.stroke",
                "stylers" : [{
                        "color" : "#e9bc62"
                    }
                ]
            }, {
                "featureType" : "road.highway.controlled_access",
                "elementType" : "geometry",
                "stylers" : [{
                        "color" : "#e98d58"
                    }
                ]
            }, {
                "featureType" : "road.highway.controlled_access",
                "elementType" : "geometry.stroke",
                "stylers" : [{
                        "color" : "#db8555"
                    }
                ]
            }, {
                "featureType" : "road.local",
                "elementType" : "labels.text.fill",
                "stylers" : [{
                        "color" : "#806b63"
                    }
                ]
            }, {
                "featureType" : "transit.line",
                "elementType" : "geometry",
                "stylers" : [{
                        "color" : "#dfd2ae"
                    }
                ]
            }, {
                "featureType" : "transit.line",
                "elementType" : "labels.text.fill",
                "stylers" : [{
                        "color" : "#8f7d77"
                    }
                ]
            }, {
                "featureType" : "transit.line",
                "elementType" : "labels.text.stroke",
                "stylers" : [{
                        "color" : "#ebe3cd"
                    }
                ]
            }, {
                "featureType" : "transit.station",
                "elementType" : "geometry",
                "stylers" : [{
                        "color" : "#dfd2ae"
                    }
                ]
            }, {
                "featureType" : "water",
                "elementType" : "geometry.fill",
                "stylers" : [{
                        "color" : "#b9d3c2"
                    }
                ]
            }, {
                "featureType" : "water",
                "elementType" : "labels.text.fill",
                "stylers" : [{
                        "color" : "#92998d"
                    }
                ]
            }
        ]
        //END STYLE
    });

    //CUSTOM MARKER ICON
    var image = {
        url : "img/ridepin.png",
        scaledSize : new google.maps.Size(150, 150)
    };
    marker = new google.maps.Marker({
            map : map,
            draggable : true,
            icon : image,
            animation : google.maps.Animation.DROP,
            position : {
                lat : 59.909144,
                lng : 10.7436936
            }
        });
    marker.addListener('click', toggleBounce);
    //END CUSTOM MARKER ICON


    // GET POSITION
    infoWindow = new google.maps.InfoWindow;

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            var pos = {
                lat : position.coords.latitude,
                lng : position.coords.longitude
            };

            infoWindow.setPosition(pos);
            infoWindow.setContent('I don\'t want this marker!');
            infoWindow.open(map);
            map.setCenter(pos);
        }, function () {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    }
    //END GET POSITION
}

//BOUNCE WHEN MARKER IS PRESSED
function toggleBounce() {
    if (marker.getAnimation() !== null) {
        marker.setAnimation(null);
    } else {
        marker.setAnimation(google.maps.Animation.BOUNCE);
    }
}
//END BOUNCE WHEN MARKER IS PRESSED
4
Streching my competence 30 Дек 2017 в 22:32

2 ответа

Лучший ответ

Используйте метод setPosition в экземпляре marker вместо использования экземпляра infoWindow.

Проверьте этот фрагмент, адаптированный из вашего кода:

var map, marker, infoWindow;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 13,
    center: {
      lat: 59.909144,
      lng: 10.7436936
    },
    disableDefaultUI: true,
    //START STYLE
    styles: [{
        "elementType": "geometry",
        "stylers": [{
          "color": "#ebe3cd"
        }]
      }, {
        "elementType": "labels.text.fill",
        "stylers": [{
          "color": "#523735"
        }]
      }, {
        "elementType": "labels.text.stroke",
        "stylers": [{
          "color": "#f5f1e6"
        }]
      }, {
        "featureType": "administrative",
        "elementType": "geometry.stroke",
        "stylers": [{
          "color": "#c9b2a6"
        }]
      }, {
        "featureType": "administrative.land_parcel",
        "elementType": "geometry.stroke",
        "stylers": [{
          "color": "#dcd2be"
        }]
      }, {
        "featureType": "administrative.land_parcel",
        "elementType": "labels.text.fill",
        "stylers": [{
          "color": "#ae9e90"
        }]
      }, {
        "featureType": "landscape.natural",
        "elementType": "geometry",
        "stylers": [{
          "color": "#dfd2ae"
        }]
      }, {
        "featureType": "poi",
        "elementType": "geometry",
        "stylers": [{
          "color": "#dfd2ae"
        }]
      }, {
        "featureType": "poi",
        "elementType": "labels.text.fill",
        "stylers": [{
          "color": "#93817c"
        }]
      }, {
        "featureType": "poi.park",
        "elementType": "geometry.fill",
        "stylers": [{
          "color": "#a5b076"
        }]
      }, {
        "featureType": "poi.park",
        "elementType": "labels.text.fill",
        "stylers": [{
          "color": "#447530"
        }]
      }, {
        "featureType": "road",
        "elementType": "geometry",
        "stylers": [{
          "color": "#f5f1e6"
        }]
      }, {
        "featureType": "road.arterial",
        "elementType": "geometry",
        "stylers": [{
          "color": "#fdfcf8"
        }]
      }, {
        "featureType": "road.highway",
        "elementType": "geometry",
        "stylers": [{
          "color": "#f8c967"
        }]
      }, {
        "featureType": "road.highway",
        "elementType": "geometry.stroke",
        "stylers": [{
          "color": "#e9bc62"
        }]
      }, {
        "featureType": "road.highway.controlled_access",
        "elementType": "geometry",
        "stylers": [{
          "color": "#e98d58"
        }]
      }, {
        "featureType": "road.highway.controlled_access",
        "elementType": "geometry.stroke",
        "stylers": [{
          "color": "#db8555"
        }]
      }, {
        "featureType": "road.local",
        "elementType": "labels.text.fill",
        "stylers": [{
          "color": "#806b63"
        }]
      }, {
        "featureType": "transit.line",
        "elementType": "geometry",
        "stylers": [{
          "color": "#dfd2ae"
        }]
      }, {
        "featureType": "transit.line",
        "elementType": "labels.text.fill",
        "stylers": [{
          "color": "#8f7d77"
        }]
      }, {
        "featureType": "transit.line",
        "elementType": "labels.text.stroke",
        "stylers": [{
          "color": "#ebe3cd"
        }]
      }, {
        "featureType": "transit.station",
        "elementType": "geometry",
        "stylers": [{
          "color": "#dfd2ae"
        }]
      }, {
        "featureType": "water",
        "elementType": "geometry.fill",
        "stylers": [{
          "color": "#b9d3c2"
        }]
      }, {
        "featureType": "water",
        "elementType": "labels.text.fill",
        "stylers": [{
          "color": "#92998d"
        }]
      }]
      //END STYLE
  });
  
  //CUSTOM MARKER ICON
  var image = {
    url: "https://maps.gstatic.com/mapfiles/ms2/micons/grn-pushpin.png",
    scaledSize: new google.maps.Size(32, 32)
  };
  marker = new google.maps.Marker({
    map: map,
    draggable: true,
    icon: image,
    animation: google.maps.Animation.DROP,
    position: {
      lat: 59.909144,
      lng: 10.7436936
    }
  });
  marker.addListener('click', toggleBounce);
  //END CUSTOM MARKER ICON

  // GET POSITION        
  infoWindow = new google.maps.InfoWindow;

  // Try HTML5 geolocation.
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var pos = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      marker.setPosition(pos);
      marker.setTitle('Your position is '+(Math.round(pos.lat * 100) / 100)+", "+(Math.round(pos.lng * 100) / 100));
      map.setCenter(pos);
    }, function() {
      handleLocationError(true, infoWindow, map.getCenter());
    });
  } else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
  }
  //END GET POSITION
}

//BOUNCE WHEN MARKER IS PRESSED
function toggleBounce() {
  if (marker.getAnimation() !== null) {
    marker.setAnimation(null);
  } else {
    marker.setAnimation(google.maps.Animation.BOUNCE);
  }
}
//END BOUNCE WHEN MARKER IS PRESSED

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
  infoWindow.setPosition(pos);
  infoWindow.setContent(browserHasGeolocation ?
                        'Error: The Geolocation service failed.' :
                        'Error: Your browser doesn\'t support geolocation.');
  infoWindow.open(map);
}
html,
body,
#map {
  margin: 0;
  padding: 0;
  height: 100%;
  max-width: none;
}
<div id="map" />

<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>

Или этот jsfiddle: https://jsfiddle.net/beaver71/n25n4ojt/

6
beaver 7 Янв 2018 в 16:40

Вероятно, вы хотите повторно использовать свой объект маркера по адресу, возвращаемому API геолокации.

Вы должны не использовать InfoWindow, а снова использовать объект-маркер:

    // GET POSITION        
            infoWindow = new google.maps.InfoWindow;

            // Try HTML5 geolocation.
            if (navigator.geolocation) {
              navigator.geolocation.getCurrentPosition(function(position) {
                var pos = {
                  lat: position.coords.latitude,
                  lng: position.coords.longitude
                };

                //comment following 3 lines, if u don't need the infowindow/label
                infoWindow.setPosition(pos);
                infoWindow.setContent('I want this marker!');
                infoWindow.open(map, marker);
                //following line re-uses your custom marker
                marker.setPosition(pos);
                map.setCenter(pos);
                }, function() {
                handleLocationError(true, infoWindow, map.getCenter());
              });
            } else {
              // Browser doesn't support Geolocation
              handleLocationError(false, infoWindow, map.getCenter());
            }
    //END GET POSITION
1
dev8080 3 Янв 2018 в 06:38