How to put a infowindow on polyline in Google Maps

2019-02-21 20:50发布

问题:

I want to know how to show infowindow on polyline in using Google Maps Api V3? and to appear in the middle of the polyline ?!

回答1:

Firstly you will need to calculate the middle/center of the polyline. This has been discussed and answered here; https://stackoverflow.com/a/9090409/787921

Then you will have to open the infowindow;

var infowindow = new google.maps.InfoWindow({
             content: "infowindow text content"});
infowindow.setPosition(midLatLng);
infowindow.open(map);


回答2:

find the middle point and set your custom view .

func showPath(polyStr :String){

    polyline?.map = nil
    mapView1.reloadInputViews()
    pathDraw = GMSPath(fromEncodedPath: polyStr)!
    polyline = GMSPolyline(path: pathDraw)

    polyline?.strokeWidth = 4.0
    polyline?.strokeColor = UIColor.init(red: 247/255.0, green: 55/255.0, blue: 76/255.0, alpha: 1.0)
    polyline?.map = mapView1


    let poinsCount = pathDraw.count()
    let midpoint = pathDraw.coordinate(at: poinsCount)

    DispatchQueue.main.async
    {
        self.addMarkerPin(corrdinate: midCordinate, distance: "10 min")
    }

}
func addMarkerPin(corrdinate:CLLocationCoordinate2D, distance: String)
{
    let marker = GMSMarker()
    marker.position = corrdinate

    PathTimeView = PathInfoView.loadFromNib() //here i am load Xib file, you can use your custom view 
    let DynamicView=PathTimeView
    DynamicView.timelbl.text = distance

    UIGraphicsBeginImageContextWithOptions(DynamicView.frame.size, false, UIScreen.main.scale)
    DynamicView.layer.render(in: UIGraphicsGetCurrentContext()!)
    let imageConverted: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

    marker.icon = imageConverted
    marker.map = self.mapView1
    marker.infoWindowAnchor = CGPoint(x: -1900 , y: -2000)
}